首页 > 解决方案 > 使用 const 和非 const 版本的运算符 [ ] 重载

问题描述

我不久前开始学习 C++,但遇到了一个问题。
我知道关于这个话题有很多类似的问题。
但是,我并没有深入理解某些东西,这就是我在这里的原因。

所以,我的问题是:
为什么我需要提供 2 个版本的 [] 运算符?
const 版本还不够吗?

例如,我一直在研究一个 Array 类:(最后两个运算符是相关的)

   class Array
    {
    private:
        int* _arrPtr;
        int _len;
    public:
        friend ostream& operator<<(ostream& out, const Array& other);
        friend istream& operator>>(istream& in, Array& other);
        Array(int len = 10, int val = 0);
        Array(const Array& other);
        ~Array();
        void setArray(int len);
        int* getArray() const;
        void setLen(int len) { this->_len = len; }
        int getLen() const { return this->_len; }
        Array operator+(const Array& other) const;
        Array& operator=(const Array& other);
        Array operator+(int val); 
        int& operator[](int index) const;
        int& operator[](int index);
    };

我可以替换这两个运算符吗

int& operator[](int index) const;
int& operator[](int index);

只有 const 的?

int& operator[](int index) const;

不会一样吗???如果只有一个 const 版本的运算符,那么对于任何运算符重载难道不是一样的吗?(假设所有 const 方法在其声明的末尾都有“const”这个词)

非常感谢你!!!

标签: c++

解决方案


是否需要两个重载取决于您要提供的接口。

const如果您希望即使在 的实例中也能够修改元素Array,那么是的,单个int& operator[](int index) const;就足够了。这就是这样std::unique_ptr做的。

但是如果你希望const Arrays 的元素是只读的,同时非const Arrays 的元素是可变的,你需要两个重载。std::vector这样做。

通常首选第二个选项。


推荐阅读