Clarity. It's common to define a meaning for an existing operator
for objects of a new class. Operators are defined as either
member functions or friend functions.
Don't use operator overloading just because it can be done
and is a clever trick.
The purpose of operator overloading is to make programs clearer
by using conventional meanings for
==
, []
, +
, etc.
For example, overloading the []
operator for a data structure
allows x = v[25]
in place of a function call.
This is purely a conveniece to the user of a class.
Operator overloading isn't strictly necessary unless other classes or functions
expect operators to be defined (as is sometimes the case).
Whether it improves program readability or causes confusion depends on how well you use it. In any case, C++ programmers are expected to be able to use it -- it's the C++ way.
//=== Point.h file ============================= Point operator+(Point p) const;
//=== Point.cpp file =========================== Point Point::operator+(Point p) const { return Point(x+p.x, y+p.y); }
//=== myprogram.cpp ============================ Point a(10, 20); Point b(1, 2); Point c = a + b;
Define a function with the keyword "operator" preceding the operator. There
can be whitespace between operator
and the operator,
but usually they are written together.
**
which is
used in some languages for exponentiation.::
, sizeof
, ?:
, or .
(dot).+
doesn't overload +=
, and similarly for the
other extended assignment operators.=
, []
, and ->
must be member functions if they are overloaded.++
and --
need special treatment because they are prefix and postfix
operators.