第二节 · 换一种走路的方式 · 递增递减运算符定义
class Array
{
private:
int data[100];
public:
// 返回引用,允许读写
int& operator[](int index)
{
return data[index];
}
// const 版本,只读
const int& operator[](int index) const
{
return data[index];
}
};
int main()
{
Array arr;
arr[0] = 42; // 调用非 const 版本
cout << arr[0] << endl;
const Array& ref = arr;
cout << ref[0] << endl; // 调用 const 版本
// ref[0] = 1; // 错误:const 不能修改
return 0;
}习题
Last updated