转换运算符和构造函数的歧义



我正在学习c++,遇到了转换运算符的问题。我正在创建一个复杂的类,它可以对复数进行基本运算。

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过载+操作员:

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

使用此代码,由于构造函数的缘故,使用带复数的double/integer进行加法可以很好地工作。

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

但是当我在类中使用转换运算符时

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

添加双/内弯工作

b = 1 + a;
// ambiguous overload

这看起来很奇怪,有人能解释一下添加转换运算符是如何产生这种歧义的吗
我在网上找不到任何资源。

在此表达式语句中

b = 1 + a;

可以使用转换构造函数将操作数CCD_ 1转换为类型complex,或者可以使用转换运算符将对象a转换为类型int。

因此,两个二进制运算符+之间存在歧义:可以使用int类型的内置运算符,也可以使用complex类型的用户定义运算符。

为了避免歧义,例如可以将转换运算符声明为显式。

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

最新更新