首页 > 解决方案 > 对程序的输出感到困惑

问题描述

我是 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; 
}

标签: c++class

解决方案


编译时:

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)); 

或者当然要删除转换运算符之一


推荐阅读