【问题标题】:Operator [ ] overloading with const and non const versions使用 const 和非 const 版本的运算符 [ ] 重载
【发布时间】:2020-12-23 02:57:48
【问题描述】:

我不久前开始学习 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”这个词)

非常感谢!!!

【问题讨论】:

  • stackoverflow.com/questions/37043078/… 回答你的问题了吗?
  • “如果只有一个 const 版本的运算符,任何运算符重载会不会都一样?” 不,不一样。你明白函数声明后的const 的真正含义吗?
  • @RSahu 有帮助,但我的问题是,如果仅用 CONST 替换 2 个运算符是否会导致相同的结果
  • @CodeLearner,您需要非常量版本才能更改容器。
  • @πάνταῥεῖ 嗯是的,我认为,一个 const 方法不能改变类的 dms。 this 的类型将是 const * .

标签: c++


【解决方案1】:

是否需要两个重载取决于你要提供什么接口。

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

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

通常首选第二个选项。

【讨论】:

  • 现在我明白我想念什么了。为什么会修改const数组,就是const。我不应该出错吗?
  • @CodeLearner 当一个函数被标记为const 时,该类的所有成员都像在其中的const 一样工作。例如。在 int&amp; operator[](int index) const; _len = ...;_arrPtr = ...; 内部确实会给你一个编译时错误。但即使指针 (_arrPtr) 变为 const,它指向的内容也不会。 *_arrPtr_arrPtr[i] 即使在 const 函数中也是允许的。这就是语言的设计方式,大概这会给你更多的灵活性。
【解决方案2】:

你不能写int&amp; operator[](int index) const;。相反,您需要编写:

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

为什么会这样?因为如果某个东西是const,那么您只能对它或它的元素进行 const 引用,因为非 const 引用可以让您更改它,而您无权这样做。

如果在事物为 const 时需要 const 引用,而在事物不是 const 时需要非 const 引用,则需要重载。如果您在任何情况下都只需要 const 引用,则可以不进行重载。

【讨论】:

  • 但它编译时没有 const。
  • @Code 在语法上可能是允许的,但允许修改const 对象的状态是否有意义? ideone.com/xySwnn
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多