【发布时间】: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++ 说调用不明确?
【问题讨论】:
-
I thought 1.11 would be clearly a float,不,像 1.11 这样的文字默认是doubles。无论哪种方式都必须进行转换,现在编译器不确定是哪一种。 -
虽然您的值可以毫无问题地进入浮点数,但这正是语言的工作方式。像 1.11 这样的文字是双精度的,因为它有一个小数部分(即不是 int),除非你明确地说它是一个浮点数
-
@Username "floats and doubles" 这些是不同的类型。 “保留两位小数”Nope
标签: c++ double overloading