c++ - 转换运算符和构造函数的歧义
问题描述
我正在学习 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;
}
加法双/int 弯腰工作
b = 1 + a;
// ambiguous overload
这看起来很奇怪,谁能解释一下添加转换运算符是如何产生这种歧义的?
我在网上找不到任何资源。
解决方案
在这个表达式语句中
b = 1 + a;
可以使用转换构造函数将操作数1
转换为复杂类型,或者可以使用转换运算符将对象 a 转换为 int 类型。
因此,两个二元运算符 + 之间存在歧义:可以使用 int 类型的内置运算符或复杂类型的用户定义运算符。
为了避免歧义,您可以例如将转换运算符声明为显式。
explicit operator int() const {
int re = real;
return re;
}
推荐阅读
- html - 将两个 div 分别对齐到父 div 的中心和末尾?
- go - 如何使用 Go API 客户端以编程方式创建 Google Cloud Function
- python - 求解绑定到复合总和的优化
- google-sheets - 如何让 MAX 返回一个数组
- sql-server - 如何将列 - 在表变量中并且具有作用于其上的函数 - 连接到永久表中的列?
- clang - 如何在 Clang 中自动注册和加载现代通行证?
- spring-boot - HATEOAS 链接中的自动装配变量
- php - 这是 PHP 中的正确清理和白名单吗
- wpf - 有没有办法在使用 AutoWireViewModel = "True" 时在 xaml 中引用 VM
- python - 同组中的 Sum 和 Listby Pandas