3

I have defined a class Complex which overloads the + operator:

Complex operator+(Complex const& x, Complex const& y);

I want to define an implicit conversion from double to Complex, such that, for example, if I write c + d, where c is a Complex and d a double, it will call my overloaded + that I defined above and return a Complex. How can I do this?

a06e
  • 18,594
  • 33
  • 93
  • 169

2 Answers2

5

You just need to define a constructor for it. This is referred to as a "converting constructor"

Complex::Complex(double x)
{
    // do conversion
}

This will allow for implicit conversion, as long as you don't use the explicit keyword, which will force you to have to use a cast to convert.

You can also define other versions of your operator+

Complex operator+(Complex const& x, double y);
Complex operator+(double x, Complex const& y);
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
4

Simply add a non-explicit constructor for Complex taking a double :

Complex(double value);

The compiler will automatically use it to implicitly convert a double to Complex.

Telokis
  • 3,399
  • 14
  • 36