今天在看书时发现了一个有意思的地方:
class TextBlock
{
public:
TextBlock(string st)
{
text=st;
}
char& operator[](size_t position)
{
return text[position];
}
private:
string text;
};
int main ()
{
TextBlock cTex("hello");
cTex[0]='k';
return 0;
}
对于:类的运算符[]重载函数:char& operator[](size_t position),其返回值是类成员text的引用,要特别当心,如果不是引用如果char operator[](size_t position),则cText[0]='K',编译器不会通过,因为此时,他只是对象text的一个副本,并不是text。上述代码中对[]重载函数的书写并不科学,只是用该例子强调返回值是引用的重要性。更科学的operator []相关写法可参考Effective C++条款3中的const成员函数。