我是C ++的新手,我正在上课。请有人帮助我。怎么了?
class Test1 {
int y;
};
class Test2 {
int x;
Test1 t1;
public:
operator Test1() { return t1; }
operator int() { return x; }
};
void fun ( int x) { };
void fun ( Test1 t ) { };
int main() {
Test2 t;
fun(t);
return 0;
}
答案 0 :(得分:3)
编译时:
t.cc: In function ‘int main()’: t.cc:18:10: error: call of overloaded ‘fun(Test2&)’ is ambiguous fun(t); ^ t.cc:13:6: note: candidate: void fun(int) void fun ( int x) { } ^~~ t.cc:14:6: note: candidate: void fun(Test1) void fun ( Test1 t ) { } ^~~
要解决这个问题,您必须表明您的选择:
fun(static_cast<Test1>(t));
或
fun(static_cast<int>(t));
或者当然删除转换运算符之一
答案 1 :(得分:2)
这是编译器错误。 Test2类中定义了两个转换运算符。因此,Test2对象可以自动转换为int和Test1。因此,函数调用fun(t)模棱两可,因为有两个函数void fun(int)和void fun(Test1),编译器无法确定要调用哪个函数。通常,转换运算符必须小心重载,因为它们可能导致歧义。