December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need to control the handling of the +=, -=, /=, and *= operators within your data type; unfortunately, these operators cannot be directly overloaded.
Overload these operators indirectly by overloading the +, -, /, and * operators, as demonstrated in Example 3-5.
Example 3-5. Overloading the +, -, /, and * operators
public class Foo
{
// Other class members...
// Overloaded binary operators
public static Foo operator +(Foo f1, Foo f2)
{
Foo result = new Foo( );
// Add f1 and f2 here...
// place result of the addition into the result variable.
return result;
}
public static Foo operator +(int constant, Foo f1)
{
Foo result = new Foo( );
// Add the constant integer and f1 here...
// place result of the addition into the result variable.
return result;
}
public static Foo operator +(Foo f1, int constant)
{
Foo result = new Foo( );
// Add the constant integer and f1 here...
// place result of the addition into the result variable.
return result;
}
// The pattern above is repeated for the -, *, and . operators as well...
}While it is illegal to overload the +=, -=, /=, and *= operators directly, you can overload 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 section of this recipe. You might notice that each ...
Read now
Unlock full access