简体   繁体   中英

Overloading compound assignment operators in C++

Why is it necessary when we overload the += operator to return a reference to the class? why the prototype is for instance ClassName& operator += (const ClassName& instance) instead of
void operator += (const ClassName& instance) ?

Several reasons.

That's what the builtin += and friends do; your overloaded version better act the same without a really good reason and documentation of the fact, or else people who use it expecting it to act like the built in ones will get upset.

The builtin ones act that way to allow them to be used as part of a larger expression like a + (b += c) .

It makes defining an overloaded operator+() in terms of operator+=() and a copy constructor easy. Consider

class foo {
  foo& operator+=(const foo &b) {
    // Do stuff
    return *this;
  }
};
foo operator+(foo a, const foo &b) { // First argument passed by value, second by reference
  return a += b;
}

Making the compound operators class members and the plain operators freestanding is a common style suggestion; it allows the first argument to be of a different type as long as it can be converted to a foo : foo b; foo a = 1 + b; foo b; foo a = 1 + b;

(All examples are very contrived for demonstration purposes)

It is because the operator += has to be a left-hand-expression .

For instance, in a += ...; there is no way the result of the evaluation of this expression won't be a left-hand-expression (ie, a += b + c + d; ).

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