![](/img/trans.png)
[英]Ternary operator applied to class with conversion operator and delete constructor causes ambiguity
[英]ambiguity with conversion operator and constructor
我正在学习 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;
}
};
我重载了 + 运算符:
complex operator+(complex a,complex b){
return complex(a.get_real()+b.get_real(),a.get_img()+b.get_img());
}
由于构造函数的原因,使用带有复数的双精度/整数添加此代码可以正常工作。
complex a(2,4);
complex b = 1+a;
但是当我在类中使用转换运算符时
operator int(){
int re = real;
return re;
}
加法双/整数弯腰工作
b = 1 + a;
// ambiguous overload
这看起来很奇怪,谁能解释一下添加转换运算符是如何造成这种歧义的?
我在网上找不到任何资源。
在这个表达式语句中
b = 1 + a;
可以使用转换构造函数将操作数1
转换为 complex 类型,或者可以使用转换运算符将对象 a 转换为 int 类型。
所以两个二元运算符 + 之间存在歧义:要么可以使用 int 类型的内置运算符,要么可以使用类型 complex 的用户定义运算符。
为避免歧义,您可以例如将转换运算符声明为显式。
explicit operator int() const {
int re = real;
return re;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.