c++ - 使用 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”这个词)
非常感谢你!!!
解决方案
是否需要两个重载取决于您要提供的接口。
const
如果您希望即使在 的实例中也能够修改元素Array
,那么是的,单个int& operator[](int index) const;
就足够了。这就是这样std::unique_ptr
做的。
但是如果你希望const
Array
s 的元素是只读的,同时非const
Array
s 的元素是可变的,你需要两个重载。std::vector
这样做。
通常首选第二个选项。
推荐阅读
- r - 如何在公式中使用带有非二进制变量的 prodlim 函数?
- api - Symfony 4.2 和 Nelmio Api Doc Bundle - 带有多个控制器的几个文档
- python - 在列表视图中获取 Django 模型以显示两者
- javascript - 如何使用画布 js 使在我的图像上制作的多边形可点击?
- selenium - 如何使用量角器使无头 chrome 工作以进行窗口身份验证弹出
- angular - 如何解决无法从角度形式读取复选框值的问题?
- json - dict到数据框,列名不正确
- android - Google Places api 会否弃用?
- algorithm - 如何使用 TimSort 按多个字段排序?
- php - Yii2:致命错误:未捕获的异常 'yii\base\InvalidConfigException'