简体   繁体   中英

What are return types of operators in C++?

I am reading the C++ Primer, in the overloaded operation chapter, the author gave an example:

// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& Sales_item::operator+=(const Sales_item&);
// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);

then, the author explained:

This difference matches the return types of these operators when applied to arithmetic types: Addition yields an rvalue and compound assignment returns a reference to the left-hand operand.

I'm not quite sure about " compound assignment returns a reference to the left-hand operand ". Can anyone elaborate on that, and relevant things, please?

It means that you can do something like the following

a = 1; 
(a += 1) += 1;

and the result will be a == 3. This is because the left most call to += modifies a and then returns a reference to it. Then the next += operates on the reference to a and again adds a number to it.

On the other hand, the normal + operator returns a copy of the result, not a reference to one of the arguments. So this means that an expression such as a + a = 3; is illegal.

a = a + b;

is also

a += b;

which is equivalent to

a.operator+= (b)

operator += supports compound assignment:

(a += b) += c;

is equivalent to

a.operator+= (b).operator+= (c);

The last line would not be possible if a value was returned instead of an rvalue.

Consider the following:

c = a + b;

is also

c = a.operator+ (b);

writing

a.operator+ (b) = c;

has no effect because the value of a is not changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM