在给定的代码中,我无法理解为什么编译器在调用函数时会产生错误。它传递的是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
是一个Test
对象,可以转换为Test2
和int
。
将其中一个转换运算符标记为explicit
将解决此问题。
在这里查看Demo。