
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Indirectly Overloading the +=, –=, /=, and *= Operators
|
119
Discussion
While it is illegal to overload the +=, -=, /=, and *= operators directly, you can over-
load them indirectly by overloading the
+, -, /, and * operators. The +=, -=, /=, and *=
operators use the overloaded +, -, /, and * operators for their calculations.
The four operators
+, -, /, and * are overloaded by the methods in the Solution sec-
tion of this recipe. You might notice that each operator is overloaded three times.
This is intentional, since a user of your object may attempt to add, subtract, multi-
ply, or divide it by an integer value. The unknown here is: which position will the
integer constant be in? Will it be in the first parameter or the second? The following
code snippet shows how this might look for multiplication:
Foo x = new Foo( );
Foo y = new Foo( );
y *= 100; // Uses: operator *(Foo f1, int multiplier)
y = 100 * x; // Uses: operator *(int multiplier, Foo f1)
y *= x; // Uses: operator *(Foo f1, Foo f2)
The same holds true for the other overloaded operators.
If these operators were being implemented in a class, you would first check whether
any were set to
null. The following code for the overloaded addition operator has
been modified to do this:
public static Foo operator +(Foo f1, Foo f2)
{
if (f1 == ...