Overload + = in C ++

If I overloaded operator + and operator = do, I still need to overload operator + = for something like this:

MyClass mc1, mc2; mc1 += mc2; 
+4
source share
4 answers

operator + = is not an integral part of + and =, so you need to explicitly overload it, since the compiler does not know how to create puzzles for you. but you can still use the already defined / overloaded operators using them inside the + = operator.

+8
source

Yes, you also need to define this.

However, the general trick is to define operator+= and then implement operator+ in terms of this, something like this:

 MyClass operator+ (MyClass lhs, const MyClass& rhs){ return lhs += rhs; } 

If you do it the other way around (use + to implement + =), you get an unnecessary copy operation in the + = operator, which may be a performance sensitive issue i.

+26
source

Yes Yes.

+7
source

If the real question here is: β€œI don’t want to write a load of duplicate statements, please tell me how to avoid this,” then the answer may be:

http://www.boost.org/doc/libs/1_38_0/libs/utility/operators.htm

The syntax looks a bit uncomfortable. Since I never used it myself, I cannot reassure you that it is simple.

+2
source

All Articles