AmbiguousfunctioncallinC++
The following code gives the compilation error of main.cpp: In function ‘int main()’:
main.cpp:18:19: error: call of overloaded ‘print(int, int)’ is ambiguous
print(0, 0);
#include <iostream>
using namespace std;
void print(int, double);
void print(double, int);
int main()
{
print(0, 0);
return 0;
}
While the following code does not give the compilation error of function call ambiguity, why so?
#include <iostream>
using namespace std;
void print(double){}
void print(int){}
int main()
{
print(0);
return 0;
}
回答
马虎地说,重载决议选择考虑参数类型的更好匹配的重载。
print(0)调用void print(int){}因为0是类型的整数文字int。
当您拨打电话时,print(0, 0)可以将第一个0转换double为 callvoid print(double, int)或将第二个转换为 call void print(int, double)。它们都不是更好的匹配,因此编译器报告了这种歧义。
有关更多详细信息,请参阅https://en.cppreference.com/w/cpp/language/overload_resolution。
请注意,这是一个选择问题。当您的示例选择调用时,宇宙不会停止膨胀,void print(double, int)因为某些规则会说这比 更好的匹配void print(int,double),这不是规则所说的。