【发布时间】:2019-03-13 10:39:40
【问题描述】:
在给定的代码中,我无法理解为什么在调用函数时编译器会产生错误。它正在传递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;
}
【问题讨论】:
-
您正在调用
fun(t),其中t的类型为Test。fun()的唯一重载接受int或Test2。因此,编译器查找Test到fun()重载将接受的其他类型的转换,并找到operator Test2()和operator int()。因此,这两个序列“将t转换为Test2并将其传递给接受Test2的fun()”和“将t转换为int并将其传递给接受@的fun()987654341@" 同样有效,编译器没有理由偏爱一个。因此调用fun(t)被诊断为模棱两可。
标签: c++ class object int operator-overloading