Operator Methods
A class can define operator methods. This is also called operator overloading. The methods can be defined for the following infix (a <op> b)
operators:
Operators
- ==,
- !=,
- >
- <
- >=,
- <=
- +,
- -
- *
- /,
- %
- &,
- |
- ^
- <<,
- >>
Operator Methods
The operator methods are named like the operation with the prefix operator, e.g. operator+().
The class operator method is used when an infix expression is executed and the left expression is found to be a class instance and the operator was implemented for that class. For example:
Point p;
p = p + 17;
would call:
Point::operator(int x)
if it is implemented. You can think of it internally being called as p.operator+(17);
All operator methods must be non-static and have exactly one argument. The type of the argument and the return type is not restricted. In general overloaded operators are expected to behave as similar as possible to the built-in operators: operator+ is expected to add, rather than multiply its arguments.
- A derived class can also call the base class operator explicitly by using the usual syntax, e.g.:
Base::operator==()
-
An operator method can also be addressed in a callFunction() call, e.g.
callFunction(object, Class::operator+, 123);
- Currently a class instance can not call an operator by name directly. E.g.
object.operator*(123);
is not allowed.