return value of operator overloading in C++

前端 未结 5 2121
逝去的感伤
逝去的感伤 2020-11-29 18:19

I have a question about the return value of operator overloading in C++. Generally, I found two cases, one is return-by-value, and one is return-by-reference. So what\'s the

5条回答
  •  余生分开走
    2020-11-29 18:51

    If you want your operator overload to behave like the built-in operator, then the rule is pretty simple; the standard defines exactly how the built-in operators behave and will indicate if the result of a built-in is an rvalue or an lvalue.

    The rule you should use is:

    • if the built-in operator returns an rvalue then your overload should return a reference
    • if the built-in returns an lvalue then your overload should return a value

    However, your overload isn't required to return the same kind of result as the built-in, though that's what you should do unless you have a good reason to do otherwise.

    For example, KennyTM noted in a comment to another answer that the stream overloads for the << and >> operators return a reference to the left operand, which is not how the built-ins work. But the designers of the stream interface did this so stream I/O could be chained.

提交回复
热议问题