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

前端 未结 5 601
予麋鹿
予麋鹿 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:43

    Consider what you are asking. You would want an expression, a + b, to return a reference to one of a or b, which would have the results of the expression. Thus you would modify one of a or b to be the sum of a and b. So you would want to redefine the semantics of the operator (+) to be the same as the operator (+=). And like @manuell said, you would thus allow (a + b) = c. The semantics you are suggesting are already offered by += and -=.

提交回复
热议问题