The following rules constrain how overloaded operators are implemented. However, they do not apply to the new and delete operators, which are covered separately in Chapter 4.
class Point
{
public:
Point operator<( Point & ); // Declare a member operator
// overload.
...
// Declare addition operators.
friend Point operator+( Point&, int );
friend Point operator+( int, Point& );
};
The preceding code sample declares the less-than operator as a member function; however, the addition operators are declared as global functions that have friend access. Note that more than one implementation can be provided for a given operator. In the case of the preceding addition operator, the two implementations are provided to facilitate commutativity. It is just as likely that operators that add a Point
to a Point
, int
to a Point
, and so on, might be implemented.
Point
,” expecting 2 to be added to the x coordinate and 3 to be added to the y coordinate.Note that the meaning of any of the operators can be changed completely. That includes the meaning of the address-of (&), assignment (=), and function-call operators. Also, identities that can be relied upon for built-in types can be changed using operator overloading. For example, the following four statements are usually equivalent when completely evaluated:
var = var + 1;
var += 1;
var++;
++var;
This identity cannot be relied upon for class types that overload operators. Moreover, some of the requirements implicit in the use of these operators for basic types are relaxed for overloaded operators. For example, the addition/assignment operator, +=, requires the left operand to be an l-value when applied to basic types; there is no such requirement when the operator is overloaded.
Note For consistency, it is often best to follow the model of the built-in types when defining overloaded operators. If the semantics of an overloaded operator differ significantly from its meaning in other contexts, it can be more confusing than useful.