为什么函数重载在C++中会产生模糊错误?

Jay*_*esh 20 c++ overloading short ambiguous c++14

在下面的代码段,在函数调用f(1),1是文字型的int并在第一功能void f(double d)参数类型是double和第二函数void f(short int i)参数类型是短整型.

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;
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 35

因为,正如您的评论所说,1是一种文字类型int.

编译器的一个隐式转换intshort int同样作为一个隐式转换为有效intdouble(CF.C++语言标准,§13.3).

因此,因为编译器无法在doubleshort int重载之间做出决定,所以它放弃并发出诊断信息.

请注意,函数参数的大小无关紧要:只是类型.

(如果编译器在运行时选择short int了调用参数适当的重载,并且double在其他实例中选择了那个,那将会很烦人.)