我想在 C++ 中为我的自定义数组类实现括号 [] 运算符。我有几个选择:
(1) Point& operator[](int index)
(2)Point& operator[](int index) const
(3)const Point& operator[](int index) const
(3) 我理解这是必需的,以防用户声明 const 对象。 但是,对于一般情况 (1, 2),我是否应该将函数设置为 const,因为该对象永远不会在函数体内被修改?
最佳答案
(1) 对于返回引用是正确的。
(2) 需要是非 const,因为您希望能够通过返回的引用修改类成员。
(3) 需要为 const
,以便可以在 const this
或等效引用上调用 []
。
编写Point&operator[](int index) const
会导致意外行为,因为您可以通过引用修改类成员。您的 Point&operator[](int index) 函数代码可能不会修改该对象,但它允许其他代码修改该对象,因为它返回对数据成员的非常量引用。因此,Point&operator[](int index) const
不是您可以提供的东西,并且编译器不应该接受提供对类数据成员的非常量访问的 const 函数。
您应该提供一个非常量版本和一个常量重载:
Point& operator[](int index);
const Point& operator[](int index) const;
关于c++ - C++ 中的括号重载运算符是否应该声明为 const 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56064545/