为什么函数重载会在 C++ 中产生不明确的错误?
Why does function overloading generate an ambiguous error in C++?
在下面的代码片段中,在函数调用 f(1)
中,1
是类型 int
的文字,在第一个函数 void f(double d)
中,参数类型是 double
和第二个函数 void f(short int i)
参数类型是 short int.
这里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;
}
因为,正如您的评论所述,1
是 int
.
类型的文字
对于编译器,int
到 short int
的隐式转换与 int
到 double
的隐式转换同样有效( cf. C++ 语言标准,§13.3).
因此,由于编译器无法在 double
和 short int
重载之间做出决定,因此它放弃并发出诊断。
请注意,函数参数的 大小 并不重要:重要的是类型。
(如果编译器在运行时选择调用参数合适的 short int
重载,而在其他情况下选择 double
重载,那将很烦人。)
在下面的代码片段中,在函数调用 f(1)
中,1
是类型 int
的文字,在第一个函数 void f(double d)
中,参数类型是 double
和第二个函数 void f(short int i)
参数类型是 short int.
这里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;
}
因为,正如您的评论所述,1
是 int
.
对于编译器,int
到 short int
的隐式转换与 int
到 double
的隐式转换同样有效( cf. C++ 语言标准,§13.3).
因此,由于编译器无法在 double
和 short int
重载之间做出决定,因此它放弃并发出诊断。
请注意,函数参数的 大小 并不重要:重要的是类型。
(如果编译器在运行时选择调用参数合适的 short int
重载,而在其他情况下选择 double
重载,那将很烦人。)