I'm a physicist trying to minimise typing out type conversions and casts in the code file intended for calculations (the equations and functions). The calculations usually involve complex numbers. So I extended the complex<double> type as cd for compactness and adding a few helping methods.
class cd: public complex<double> { ... }
Now if in the calculations I have instances like
int i = 2;
cd z(1,2);
cout << i*z;
This gives an error as there is no operator that multiplies an int and cd. (tbh I thought c++ would automatically implicitly convert the int to a double and use the relevant operator.) Upon defining such an operator manually as such
cd operator*(const int& i, const cd& z)
{
return cd(i*z.real(),i*z.imag());
}
c++ then warns about ambiguity of type-conversion for parts like
double x = 30;
x*z;
Since the manual operator definition (above) can also be used for a double with cd - which is already defined in the standard library.
In addition to this, I would also like a conversion from cd to double so that complex numbers can be passed (without the need for explicitly converting) to functions that take real (double type) arguments.
Only the operator* has been given here for example, but I'd like to do this for other math binary operations too.
Aucun commentaire:
Enregistrer un commentaire