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?

+3


source to share


2 answers


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);

      

+5


source


Just add a constructor not explicit

for Complex

by taking double

:

Complex(double value);

      



The compiler will automatically use it to implicitly convert double

to Complex

.

+4


source







All Articles