Why we use reference return in assignment operator overloading and not at plus-minus ops?

前端 未结 5 586
予麋鹿
予麋鹿 2021-02-01 07:19

As I read in books and in the web, in C++ we can overload the \"plus\" or \"minus\" operators with these prototypes (as member functions of a class Money):

5条回答
  •  囚心锁ツ
    2021-02-01 07:28

    I think its fine if you return by value in overloaded assignment operator , that is because of associativity of assignment operator. consider this:

    int a = b =c = 3 ;

    here associativity is as followed: (a=(b=(c=3)))

    but consider iostream operation cout << x << y << z ;

    here associativity is as followed: (((cout << x )<< y) << z) ;

    you can see that x will be printed first , so if you return by value in overloading of << operator , return value will not be "lvalue" , while returning by refrence is a lvalue , so cascading of << operator can be achieve.

    one more point , copy constructor will get called if you return by value. ( which is not the case with return by refrence)

提交回复
热议问题