Syntax
Defining an overloaded
operator is like defining a function, but the name of
that function is operator@, in which @ represents the operator
that’s being overloaded. The number of arguments in the overloaded
operator’s argument list depends on two
factors:
- Whether it’s a unary
operator (one argument) or a binary operator (two
arguments).
- Whether
the operator is defined as a global function (one argument for unary, two for
binary) or a member function (zero arguments for unary, one for binary –
the object becomes the left-hand
argument).
Here’s a
small class that shows the syntax for operator overloading:
//: C12:OperatorOverloadingSyntax.cpp
#include <iostream>
using namespace std;
class Integer {
int i;
public:
Integer(int ii) : i(ii) {}
const Integer
operator+(const Integer& rv) const {
cout << "operator+" << endl;
return Integer(i + rv.i);
}
Integer&
operator+=(const Integer& rv) {
cout << "operator+=" << endl;
i += rv.i;
return *this;
}
};
int main() {
cout << "built-in types:" << endl;
int i = 1, j = 2, k = 3;
k += i + j;
cout << "user-defined types:" << endl;
Integer ii(1), jj(2), kk(3);
kk += ii + jj;
} ///:~
The two overloaded operators are defined
as inline member functions that announce when they are called. The single
argument is what appears on the right-hand side of the operator for binary
operators. Unary operators have no arguments when defined as member functions.
The member function is called for the object on the left-hand side of the
operator.
For non-conditional operators
(conditionals usually return a Boolean value), you’ll almost always want
to return an object or reference
of the same type you’re operating on if the two arguments are the same
type. (If they’re not the same type, the interpretation of what it should
produce is up to you.) This way,
complicated
expressions can be built up:
kk += ii + jj;
The operator+ produces a new
Integer (a temporary) that is used as the rv argument for the
operator+=. This temporary is destroyed as soon as it is no longer
needed.