What are the return types of operators in C ++?

I am reading a C ++ Primer, in the chapter with an overloaded operation, 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 corresponds to the return data types of these operators when applied to arithmetic types: adding gives the assignment of rvalue and join, returns a link to the left operand.

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

+6
source share
2 answers

That means you can do something like the following

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

and the result will be == 3. This is due to the fact that the leftmost call + = changes a , and then returns a link to it. Then the next + = works with a reference to a and adds the number to it again.

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

+5
source
 a = a + b; 

also

 a += b; 

which is equivalent

 a.operator+= (b) 

operator + = supports compound assignment:

 (a += b) += c; 

equivalently

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

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

Consider the following:

 c = a + b; 

also

 c = a.operator+ (b); 

write

 a.operator+ (b) = c; 

does not affect, because the value of a does not change.

+2
source

Source: https://habr.com/ru/post/914857/


All Articles