【问题标题】:Why does function overloading generate an ambiguous error in C++?为什么函数重载会在 C++ 中产生模棱两可的错误?
【发布时间】:2018-03-02 10:05:12
【问题描述】:

在下面的代码 sn-ps 中,在函数调用 f(1) 中,1int 类型的文字,在第一个函数中 void f(double d) 参数类型是 double 和第二个函数 void f(short int i) 参数类型是短整数

这里1int类型不是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;
}

【问题讨论】:

标签: c++ c++14 overloading short ambiguous


【解决方案1】:

因为,正如您的评论所指出的,1int 类型的文字。

对于编译器,intshort int 的隐式转换与 intdouble 的隐式转换同样有效(cf。C++ 语言标准,§ 13.3)。

因此,由于编译器无法在 doubleshort int 重载之间做出决定,它放弃并发出诊断。

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

(如果编译器在运行时选择 short int 重载(如果调用参数合适),而在其他情况下选择 double 重载,那会很烦人。)

【讨论】:

  • 关于你的最后一句话,有点讽刺的是f(0) 确实可以导致与int a=0; f(a); 不同的重载解决方案。但这当然是添加nullptr 的原因。
猜你喜欢
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多