2

Just curious about how to overload them.

The opAssign operators are like addAssign(+=) and subAssign(-=).

"globally" means they are not overloaded as member functions, but just a operator act on operands

For these opAssign operators, they are binary operators.(they receive two operands) Therefore two parameters are needed.

I found no examples on the web.....

markus
  • 40,136
  • 23
  • 97
  • 142

2 Answers2

9

Here's a trivial example of defining operator+=:

struct Foo{
    int x;
};

Foo& operator+=(Foo& lhs, const Foo& rhs) {
    lhs.x += rhs.x;
    return lhs;
}
Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
sepp2k
  • 363,768
  • 54
  • 674
  • 675
3

The assignment operator (=) is special in that it always needs to be a non-static member function as per "§13.5.3 Assignment" of the C++ standard.

An assignment operator shall be implemented by a non-static member function with exactly one parameter

The same is true for the function call operator and the subscript operator. Other "assignment" operators (+=, -=, *=, etc) can be free binary functions.

Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
sellibitze
  • 27,611
  • 3
  • 75
  • 95
  • ASFAIU Bossliaw was asking about the operators that combine assignment with some other operation (`+=` etc.), not about pure assignment (`=`). – sbi Oct 04 '09 at 22:17
  • Tried to realize this: The Microsoft-Compiler seems to ignore the ´non-static member function´ overloading the '='-operator. Why is this? – Sam Ginrich Apr 06 '22 at 12:56