operator=返回引用
令operator=返回一个引用
关于赋值对于普通变量如下
int x,y,z;
x = y = z =10;
采用从右到左的结合律。
也就是:
X = (y = (z = 10));
先赋值给z,然后将z的值赋值给y,然后再将y的值赋值给x。
那么在对于对象如何实现呢?请看例子
class pe
{
private:
int x{ 0 };
int y{ 0 };
int z{ 0 };
public:
pe(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
pe() = default;
pe & operator=(const pe &o)
{
this->x = o.x;
this->y = o.y;
this->z = o.z;
return *this;
}
void print()
{
cout << this->x << " " << this->y << " " << this->z << endl;;
}
};
void playxx()
{
pe p1(1, 2, 3);
pe p2, p3, p4;
p2 = p3 = p4 = p1;
p1.print();
p2.print();
p3.print();
p4.print();
}
int main()
{
playxx();
system("pause");
}
结果:
其实在运算符重载的时候返回引用即可实现。