【问题标题】:int and float in function overloading函数重载中的 int 和 float
【发布时间】:2015-12-10 17:42:07
【问题描述】:

我有两个重载函数,如下所示:

void print(int i) { ... }
void print(float f) { ... }

它给了我print(1.2); 的这个错误:

error: call of overloaded 'print(double)' is ambiguous 

谁能解释一下为什么?

【问题讨论】:

  • 你想要哪种转换?双 -> int 或双 -> 浮动?
  • 恰巧C++指定double->intdouble->float同样有效。其中一个本可以做得比另一个更好,但这不是做出的决定。
  • 试试这个:print(1.2f);

标签: c++ floating-point int overloading


【解决方案1】:

1.2 是双精度字面量而非浮点数。

所以编译器需要明确的消歧。

1.2f 可以工作,因为它是一个浮点文字。

【讨论】:

    【解决方案2】:

    1.2double 文字,使您尝试调用的函数不明确 - double 可以很容易地截断为 floatint。使用 float 文字 (1.2f) 或显式转换可以解决问题。

    【讨论】:

      【解决方案3】:

      它将 1.2 解释为双精度数。将其转换为浮点数将解决问题。

      打印(浮动(1.2));

      【讨论】:

      • 加一个,但严格来说,后缀 f 不是演员表。
      猜你喜欢
      • 2017-07-26
      • 2013-10-01
      • 1970-01-01
      • 2016-07-22
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多