重载函数的调用不明确,double 与 float [重复]

问题描述 投票:0回答:1

每当我运行此代码时...

#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个回答
6
投票

在 C++ 中,像

1.11
这样的十进制文字类型被定义为 double。鉴于它必须将双精度转换为
int
float
,这会导致歧义。

带有

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

© www.soinside.com 2019 - 2024. All rights reserved.