【发布时间】: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++