C++中赋值运算符的返回值通常为this对象的引用:
class A{
public:
A(int i):m(i){}
A& operator=(const A& a)
{
m = a.m;
return *this;
}
int m = 0;
};
之所以这样做,是因为原生类型,比如int型变量允许做这样的操作:
int i = 1;
( i = 8 ) = 0;
cout<<i<<endl; //输出:0
虽然我不太理解,( i = 8 ) = 0;这样操作的意义是什么,不过原生类型确实允许这样的操作。
为了让自定义的类型也具备这样的能力,因此要让赋值运算符的返回值为this对象引用:
#include <iostream>
using namespace std;
class A{
public:
A(int i):m(i){}
A& operator=(const A& a)
{
m = a.m;
return *this;
}
int m = 0;
};
int main()
{
A a1(1);
(a1 = 8) = 0;
cout<<a1.m<<endl; //输出:0
return 0;
}
如果赋值运算符的返回值类型为this对象的常量引用,是无法完成(a1 = 8) = 0;这样的操作的: