
316
LESSON 26 OverlOading OperatOrs
ComplexNumber - double
double - ComplexNumber
1. You can use code similar to the following:
// ComplexNumber + ComplexNumber.
public static ComplexNumber operator +(ComplexNumber me, ComplexNumber other)
{
return new ComplexNumber(
me.Real + other.Real,
me.Imaginary + other.Imaginary);
}
// ComplexNumber + double.
public static ComplexNumber operator +(ComplexNumber me, double x)
{
return new ComplexNumber(me.Real + x, me.Imaginary);
}
// double + ComplexNumber.
public static ComplexNumber operator +(double x, ComplexNumber other)
{
return other + x;
}
// ComplexNumber * ComplexNumber.
public static ComplexNumber operator *(ComplexNumber me, ComplexNumber other)
{
return new ComplexNumber(
me.Real * other.Real - me.Imaginary * other.Imaginary,
me.Real * other.Imaginary + me.Imaginary * other.Real);
}
// ComplexNumber * double.
public static ComplexNumber operator *(ComplexNumber me, double x)
{
return new ComplexNumber(me.Real * x, me.Imaginary * x);
}
// double * ComplexNumber.
public static ComplexNumber operator *(double x, ComplexNumber other)
{
return other * x;
}
// Unary -.
public static ComplexNumber operator -(ComplexNumber me)
{
return new ComplexNumber(-me.Real, -me.Imaginary);
}
596906c26.indd 316 4/7/10 12:34:04 PM