令operator=返回一个reference to *this
int main() { int a, b, c = 5; a = b = c; cout << a; }
这个代码,很明显输出的是5。所以我们在写这种连续赋值的时候,其对应的赋值运算符应当返回一个*this :
class A { public: A(string ss, int x) :s(ss), a(x) {}; A& operator=(const A& aa) { this->a = aa.a; this->s = aa.s; return *this; } friend ostream& operator<<(ostream& out,A& aa); private: string s; int a; }; ostream& operator<<(ostream& out,A& aa) { out << aa.a<<" "<<aa.s; return out; } int main() { A a("a", 1); A b("b", 2); A c("c", 3); a = b = c; cout << a << endl; cout << b << endl; cout << c << endl; }
结果符合预期!