考虑下面代码:
#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;