2016-06-21 141 views
-1

为什么我没有得到输出。我期待有趣(Test2)称为输出。由于函数传递的参数不同,所以不应该有任何冲突。C++运算符超载冲突

#include <iostream> 
using namespace std; 
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; 
} 
+1

IMO,铸造操作员是C++语言中滥用最多的部分之一。而且,当你编写散布的代码时,你不会知道或忘记哪个函数实际被调用,并且可能导致程序下降到一个意想不到的执行路径。即使你的代码编译完成,你甚至不确定哪个函数会被调用。 – PaulMcKenzie

回答

3

您对fun()的呼叫不明确。 t的类型为Test,它可以转换为Test2int,因此两个fun实现都是候选。

+1

总之,调用者必须自己解决模糊性问题,例如通过调用't'上的'static_cast' – KABoissonneault