How to define implicit conversion from double?
I have defined a class Complex
that overloads the operator +
:
Complex operator+(Complex const& x, Complex const& y);
I want to define an implicit conversion from double
in Complex
, for example, if I write c + d
, where c
is Complex
and d
a double
, it will cause my overloaded +
, which I have defined above, and returned Complex
. How can i do this?
source to share
You just need to define a constructor for it. This is called the conversion constructor
Complex::Complex(double x)
{
// do conversion
}
This will allow an implicit conversion if you are not using a keyword explicit
that will force you to use the converted conversion.
You can also define other versions of your operator+
Complex operator+(Complex const& x, double y);
Complex operator+(double x, Complex const& y);
source to share