运算符重载和函数重载产生不明确的编译器错误

operator overloading and function overloading producing ambiguous compiler error

本文关键字:重载 编译器 错误 不明确 函数 运算符      更新时间:2023-10-16

在给定的代码中,我无法理解为什么编译器在调用函数时会产生错误。它是传递test类的对象,该类具有test2类的数据成员

class Test2 {
int y;
};
class Test {
int x;
Test2 t2;
public:
operator Test2 () {return t2;}
operator int () {return x;}
};
void fun (int x) { 
cout << "fun(int) called";
}
void fun (Test2 t) {
cout << "fun(Test 2) called";
}
int main() {
Test t;
fun(t);
return 0;
}

我无法理解为什么编译器在调用函数时会产生错误

编译器应该如何确定要调用哪个函数?在与名称func关联的重载集中有两个函数,以及两个运算符,它们允许隐式转换为与此重载集的两个函数参数同样匹配的类型。

情况与

void f(long);
void f(short);
f(42); // Error: both conversions int -> log and int -> short possible

您可以通过以下方式修复它,例如

fun(static_cast<Test2>(t)); // be explicit on the calling side

或者将一个(或两个)转换运算符标记为explicit

explicit operator Test2 () {return t2;}

这将禁用到Test2的隐式转换,并且需要显式强制转换,如前所示。

调用fun(t);不明确,因为fun的两个重载都有资格使用它。

这又是因为t是一个可以转换为Test2intTest对象。

将任一转换运算符标记为explicit将解决此问题。

在此处查看演示