[英]ambiguity with conversion operator and constructor
I am learning c++, faced a problem with conversion operator.我正在学习 C++,遇到了转换运算符的问题。 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.可以使用转换构造函数将操作数
1
转换为 complex 类型,或者可以使用转换运算符将对象 a 转换为 int 类型。
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.所以两个二元运算符 + 之间存在歧义:要么可以使用 int 类型的内置运算符,要么可以使用类型 complex 的用户定义运算符。
To avoid the ambiguity you could for example declare the conversion operator as explicit.为避免歧义,您可以例如将转换运算符声明为显式。
explicit operator int() const {
int re = real;
return re;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.