effective c++ 中有这样一段代码:
class T {
public:
const char& operator[] (size_t p) const
{
return text[p];
}
char& operator[] (size_t p)
{
return const_cast<char &>(static_cast<const T&>(*this)[p]);
}
T(string s) : text(s) {}
private:
string text;
};
int main()
{
T tb("Hello");
cout << tb[0];
const T ctb("World");
cout << ctb[0];
return 0;
}
即使不定义non-const版本, tb[0] 也会自动匹配const版本的[ ], 那定义non-const是为了什么? 有什么好处?