条款10:令 operator= 返回一个reference to *this
Have assignment operators return a reference to *this.
关于复制,程序中通常会出现连锁形式:
int x, y, z;
x = y = z = 15; // x = (y = (z = 15)));
为了实现“连锁赋值”,赋值操作符必须返回一个 reference 指向操作符的左侧实参,这时 class 实现赋值操作符时应该遵循的协议:
class Widget {
public:
...
Widget& operator=(const Wedget& rhs) {
...
return *this;
}
...
};
这个协议适用于所有赋值相关的运算。
Last updated
Was this helpful?