【问题标题】:call of overloaded function is ambiguous, double vs float [duplicate]重载函数的调用不明确,double vs float [重复]
【发布时间】:2016-01-23 14:09:34
【问题描述】:

每当我运行这段代码时...

#include <iostream>

int add(int x, int y){
    return x+y;
} 

float add(float x, float y){
    return x+y;
}

int main(){
    using namespace std;
    add(1.11, 1.11);
    return 0;
}

...我收到此错误:

18.cpp: In function ‘int main()’:
18.cpp:24:16: error: call of overloaded ‘add(double, double)’ is ambiguous
  add(1.11, 1.11);
                ^
18.cpp:24:16: note: candidates are:
18.cpp:7:5: note: int add(int, int)
 int add(int x, int y){
     ^
18.cpp:11:7: note: float add(float, float)
 float add(float x, float y){

我认为 1.11 显然是浮点数,而不是整数。当我将float 更改为double 时,程序可以运行。

为什么 C++ 说调用不明确?

【问题讨论】:

标签: c++ double overloading


【解决方案1】:

在 C++ 中,像 1.11 这样的十进制字面量的类型被定义为双精度。鉴于它必须将双精度转换为intfloat,这会导致歧义。

带有f 后缀的文字如1.11f 将具有float 类型。

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多