重载下标操作符的一大好处便是对对象内部的容器可以像访问数组元素一样进行读写。
如果重载的下标操作符不返回引用,便只能读取对象的内部状态。
#include <vector>
using std::vector;
#include <iostream>
using std::cout; using std::endl;
class Foo {
public:
Foo(): data(100) { for (int i = 0; i != 100; ++i) data[i] = i; }
int operator[](const size_t);
//const int operator[](const size_t) const;
// other interface members
private:
vector<int> data;
// other member data and private utility functions
};
int Foo::operator[](const size_t index)
{
return data[index]; // no range checking on index
}
int main() {
Foo f;
cout << f[50] << endl; //相当于cout << f.operator[](50) << endl;
f[50] = 90; //相当于f.operator[](50) = 90;
cout << f[50] << endl;
system("pause");
return 0;
}
f[50]相当于调用了成员函数f.operator[](50),由于不是返回引用,那么函数在返回的地方会创建一个临时整形变量,并用f.data[50]进行初始化,所以即使可以赋值,也仅仅是对临时对象进行赋值。但如果该函数返回的是引用的话,那么函数调用结束后并不会创建临时变量保存运算结果,而是直接把f.data[50]放在调用结束处,因此是可以改写对象的内部状态的。这便是返回引用的好处。