链式赋值为何要返回&

#include<iostream>

using namespace std;

class A{
public:
    A(int x_):x(x_){};
    A/*&*/ operator =(A& h)/*&*/;       //加上后置&就不合法,默认情况他同时支持向左值(&)和右值(&&)赋值
    friend ostream& operator << (ostream& out,const A & h);
private:
    int x;
};
    inline A A::operator =(A& h)
    {
        x = h.x;
        return *this;
    }

    ostream& operator << (ostream& out,const A & h)
    {
        out << h.x;
        return out;
    }
int main(void)
{
    A q(1);
    A w(2);
    A e(3);
    cout << q << " " << w << " " << e << endl;

    //q = w = e;


    (q = w) = e ;   //把值赋给了临时右值
    cout << q << " " << w << " " << e << endl;
    return 0;
}

 

posted @ 2016-07-29 16:36  真!白  阅读(235)  评论(0)    收藏  举报