gpt4 book ai didi

c++ - 使用 const 和非 const 版本的运算符 [ ] 重载

转载 作者:行者123 更新时间:2023-12-02 09:52:11 24 4
gpt4 key购买 nike

我不久前开始学习 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”这个词)
非常感谢你!!!

最佳答案

是否需要两个重载取决于您要提供的接口(interface)。
如果您希望能够在 const 中修改元素Array 的实例,那么是的,单 int& operator[](int index) const;足够。这就是 std::unique_ptr 做。
但是如果你想要 const 的元素Array s 是只读的,同时非 const 的元素Array s 是可变的,你需要两个重载。 std::vector 这样做。
通常首选第二个选项。

关于c++ - 使用 const 和非 const 版本的运算符 [ ] 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63730953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com