您的位置:首页 > Web前端

条款10:令operator=返回一个reference to * this

2014-08-19 19:54 471 查看
考虑下面代码:

#include <iostream>
using namespace std;

class Dream
{
public:
Dream():a(0){}
Dream(int b):a(b){}
void operator=(const Dream& rhs)
{
a=100;
}
private:
int a;
};
int main()
{
Dream d1(10);
Dream d2;
d2=d1; //d2 100 。d1 10 说明自定义的赋值操作符(函数体为了测试,随便写的)
return 0;
}
也就是赋值操作符,如果仅限2个数的时候,可以。但是a=b=c的时候就错误了。

如果对于下面连锁赋值:这样的操作就不行了

int x, y, z;
x = y = z = 15;
实际顺序:

x = (  y = (z = 15)  );
为了实现”连锁赋值“赋值操作符必须返回一个reference指向操作符的左侧实参。

class Widget {
public:
...
Widget& operator=(const Widget& rhs) {
...;
return *this;
}
};


请记住:令赋值(assignment)操作符返回一个 reference to * this;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: