C++:重载 [ ] 运算符以进行读写访问

C++: Overloading the [ ] operator for read and write access

本文关键字:读写 写访问 运算符 重载 C++      更新时间:2023-10-16

通常,如何声明读取和写入访问的类的索引[ ]运算符?

我尝试了类似的东西

/**
 * Read index operator.
 */
T& operator[](T u);
/**
 * Write index operator
 */
const T& operator[](T u);

这给了我错误

../src/Class.h:44:14: error: 'const T& Class::operator[](T)' cannot be overloaded
../src/Class.h:39:8: error: with 'T& Class::operator[](T)'

您的可变版本很好:

T& operator[](T u);

const版本应该是const成员函数,并返回const引用:

const T& operator[](T u) const;
                         ^^^^^

这不仅将其与其他重载区分开来,而且还允许(只读)访问类的const实例。通常,重载成员函数可以通过其参数类型和常量/易失性限定来区分,但不能通过其返回类型来区分。

你只有一个重载,用于读取和写入:

T& operator[](int);

话虽如此,您可能还希望有一个const重载:

const T& operator[](int) const;

这将提供对类const实例的只读索引。

您会收到错误,因为重载函数不能仅因返回类型而异。但它们的常量可能不同。

/**
 * Write index operator.
 */
T& operator[](T u);
/**
 * Read index operator
 */
const T& operator[](T u) const;

注意"写入"和"读取"交换的位置。

另外,你实际上不是说运算符的参数是某种整数类型吗?