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 .
Here 1
is an int
type not a double
type, then Why does compiler generated ambiguous error?
#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
.
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).
Thus, because the compiler can't decide between the double
and short int
overloads, it gives up and issues a diagnostic.
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.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.