Operator Overloading
Operators
in C++ may be overloaded in the same way that functions are
overloaded. In C, the + (plus) operator is "overloaded" to work
for int or float values. In C++, this concept is extended to
include class types.
Notes:
- You may overload the following operators:
+ - *
/ % ^
& |
~
! , =
< > <= >=
++ -- <<
>> == !=
&& ||
+=
-+ /= %= ^=
&= |= *=
<<= >>= [] () -> ->* new delete
- Most operators may be overloaded, both binary and unary operators. The following operators may not be overloaded:
. direct member
.* direct pointer to member
:: scope resolution
? : ternary
- To overload an operator, create a function called operator@ where @ is the operator symbol you wish to overload.
- Operator precedence is still in effect for overloaded operators and may not be changed.
- Default arguments are not allowed in overloaded operator functions.
- For an expression involving binary operators, A + B means:
A.operator+(B) if operator+() is a class member function
operator+(A,B) if operator+() is a non-class member function
- An overloaded operator function may be defined as a class member function, a friend function, or even a non-friend function.
- You
may not overload an operator (redefine) for the built-in primitive
types. In other words, if a and b are ints, then a+b will always
be (int) a+b.
- You may not create any new operator symbols