条款-10 令 operator= 返回一个 reference to *this
- 令赋值(saaignment)操作符返回一个 reference to *this。
常量有以下赋值连锁形式:
int x, y, z;
x = y = z = 15;
// x = ( y = (z = 15) )
// 15先被赋值给z,然后其结果(更新后的z)再被赋值给y,同理赋值给x。
为了实现“连锁赋值”,赋值操作符必须返回一个 reference指向操作符的左侧实参。在 copy assignment操作符里返回 *this 即可:
class widget {
public:
……
widget& operator= ( const widget& rhs ) {
……
return *this;
}
……
};
同理适用于 +=、-+、*=