首页 > 解决方案 > C++ 中的括号重载运算符是否应该声明为 const 函数?

问题描述

我想在 C++ 中为我的自定义 Array 类实现一个括号 [] 运算符。我有几个选择:

(1) Point& operator[](int index)
(2) Point& operator[](int index) const
(3)const Point& operator[](int index) const

(3) 如果用户声明一个 const 对象,我理解是必需的。但是,对于一般情况 (1, 2),我应该将函数设为 const,因为该对象从未在函数体中被修改过吗?

标签: c++operator-overloading

解决方案


(1) 返回引用是正确的。

(2) 需要是非的const,因为您希望能够通过返回的引用来修改类成员。

(3) 需要const如此[]才能调用上一个const this或等效的引用。

写入Point& operator[](int index) const会导致意外行为,因为您可以通过引用修改类成员。您的Point& operator[](int index)函数代码可能不会修改对象,但它允许其他代码修改对象,因为它返回对数据成员的非常量引用。所以Point& operator[](int index) const不是你可以提供的,编译器不应该接受提供对类数据成员的非常量访问的 const 函数。

相反,您应该提供一个非常量版本和一个 const 重载:

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

推荐阅读