Moray
Moray

Reputation: 321

Type conversions to custom class - C++

I have a class of complex numbers, loaded the +, -, *, /,=,!= operators both with complex and double types on both ways but when I write the code complex z = 1, the compilers gives me an error saying that there are no variable conversion from int to complex. Although, it accepts the code

complex z;
z = 1;

and everything works fine. How can I fix this error?

Upvotes: 0

Views: 208

Answers (4)

jrok
jrok

Reputation: 55395

The line complex z = 1 does Copy Initialization. You'll need an appropriate constructor:

complex::complex(int i) // or double or whatever is convertible to int by
{                       // implicit conversion
    // your code
}

This is different than

complex z;
z = 1;

which is assignment (to a previously default constructed object) that requires an assignment operator.

Upvotes: 2

Andy Prowl
Andy Prowl

Reputation: 126432

You may want add a constructor which accepts a double:

class complex
{
public:
    complex(double d) : _real(d), _imag(0) { }
    ...
};

Be careful, though: this will make it possibly to pass an int wherever a complex is expected, because your constructor will perform an implicit conversion.

Upvotes: 1

Daniel Frey
Daniel Frey

Reputation: 56863

You need a constructor that takes a double.

class complex
{
public:
    complex( double d );
};

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

You need to write an appropriate constructor.

class complex {
public:
    complex(double x) {
        // ...
    }

    // ...
};

Upvotes: 0

Related Questions