[英]Why does function overloading generate an ambiguous error in C++?
In the following code snippets, In function call f(1)
, 1
is a literal of type int
and in first function void f(double d)
argument type is double
and second function void f(short int i)
argument type is short int . 在下面的代码片段中,在函数调用f(1)
, 1
是int
类型的文字,在第一个函数中void f(double d)
参数类型是double
和第二个函数void f(short int i)
参数类型是short int 。
Here 1
is an int
type not a double
type, then Why does compiler generated ambiguous error? 这里1
是int
类型而不是double
类型,那么为什么编译器生成了模糊错误?
#include <iostream>
using namespace std;
void f(double d) // First function
{
cout<<d<<endl;
}
void f(short int i) // Second function
{
cout<<i<<endl;
}
int main()
{
f(1); // 1 is a literal of type int
return 0;
}
Because, as your comment notes, 1
is a literal of type int
. 因为,正如您的注释所指出的那样, 1
是int
类型的文字。
To the compiler, an implicit conversion of int
to short int
is equally as valid as an implicit conversion of int
to double
( cf . the C++ language standard, §13.3). 对于编译器, int
到short int
的隐式转换与int
到double
的隐式转换一样有效( 参见 C ++语言标准,§13.3)。
Thus, because the compiler can't decide between the double
and short int
overloads, it gives up and issues a diagnostic. 因此,因为编译器无法在double
和short int
重载之间做出决定,所以它会放弃并发出诊断信息。
Note that the magnitude of the function parameter doesn't matter: just the type. 请注意,函数参数的大小无关紧要:只是类型。
(It would be annoying if the compiler chose, at runtime, the short int
overload if the calling argument was appropriate, and the double
one in other instances.) (如果编译器在运行时选择了调用参数适当的short int
重载,而在其他实例中选择了double
,则会很烦人。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.