函数重载中的 int 和 float
int and float in function overloading
我有两个重载函数如下:
void print(int i) { ... }
void print(float f) { ... }
它给了我 print(1.2);
这个错误:
error: call of overloaded 'print(double)' is ambiguous
谁能解释一下为什么?
1.2 是双字面量而不是浮点数。
因此编译器需要显式消歧。
1.2f 可以工作,因为它是一个浮点数。
它将 1.2 解释为双精度数。将其转换为浮点数即可解决问题。
打印(浮动(1.2));
1.2
是一个 double
文字,使您试图调用的函数不明确 - double
可以很容易地截断为 float
或到 int
。使用 float
文字 (1.2f
) 或显式转换它可以解决问题。
我有两个重载函数如下:
void print(int i) { ... }
void print(float f) { ... }
它给了我 print(1.2);
这个错误:
error: call of overloaded 'print(double)' is ambiguous
谁能解释一下为什么?
1.2 是双字面量而不是浮点数。
因此编译器需要显式消歧。
1.2f 可以工作,因为它是一个浮点数。
它将 1.2 解释为双精度数。将其转换为浮点数即可解决问题。
打印(浮动(1.2));
1.2
是一个 double
文字,使您试图调用的函数不明确 - double
可以很容易地截断为 float
或到 int
。使用 float
文字 (1.2f
) 或显式转换它可以解决问题。