简体   繁体   中英

ambiguity with conversion operator and constructor

I am learning c++, faced a problem with conversion operator. I am creating a complex class that can do basic operations on complex number.

class complex
{
    double real, img;

public:
    complex(double re=0,double im=0){
        real = re;
        img = im;
    }
    double get_real() const{
        return real;
    }
    double get_img() const{
        return img;
    }

};

I overloaded + operator:

complex operator+(complex a,complex b){
    return complex(a.get_real()+b.get_real(),a.get_img()+b.get_img());
}

With this code addition with double/integer with complex number works fine because of the constructor.

complex a(2,4);
complex b = 1+a;

But when I use a conversion operator inside the class

operator int(){
    int re = real;
    return re;
}

Addition with double/int stooped working

b = 1 + a;
// ambiguous overload

This seems weird, can anyone please explain how adding the conversion operator is creating this ambiguity?
I could not find any resource online.

In this expression statement

b = 1 + a;

either the operand 1 can be converted to the type complex using the conversion constructor or the object a can be converted to the type int using the conversion operator.

So there is an ambiguity between two binary operators +: either the built-in operator for the type int can be used or the user-defined operator for the type complex can be used.

To avoid the ambiguity you could for example declare the conversion operator as explicit.

 explicit operator int() const {
        int re = real;
        return re;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM