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 =

C++中,赋值运算符operator=返回this对象的引用,以便支持连续赋值如a1 = a2 = 5。尽管原生类型允许(i = 8) = 0的操作,但这种用法并不常见。Effective C++条款10提到这个设计,然而实际用途可能不局限于该解释。
订阅专栏 解锁全文

9687

被折叠的 条评论
为什么被折叠?



