Multiplication with overloaded operator
I have a complex class CComplex.
I am able to do the following operation using overloading.
CComplex A;
CComplex B;
B = A * 2;
But, I am unable to figure out how to do B = 2 * A;
Is this possible?
Regards,
Kiran
[269 byte] By [
kirankn] at [2007-11-20 11:45:44]

# 1 Re: Multiplication with overloaded operator
Yes, its possible. You need a non-member operator* function that takes a double and a CComplex and returns a CComplex:
// needed for r * c
CComplex operator*( const double op1, const CComplex& op2 )
{
// assuming there is a specialized CComplex constructor taking the real/imag parts
return CComplex( op1 * op2.real, op1 * op2.imag );
}
// needed for c * r
CComplex operator*( const CComplex& op1, const double op2 )
{
// assuming there is a specialized CComplex constructor taking the real/imag parts
return CComplex( op2 * op1.real, op2 * op1.imag );
}
I chose to use the double type because int/float are implicitely convertible to double, so you dont have to provide these operatores for integers or floats.