【问题标题】:Function overloading in C++. Does not work with float, works with double [duplicate]C++中的函数重载。不适用于 float,适用于 double [重复]
【发布时间】:2015-06-17 08:35:24
【问题描述】:
#include <iostream>

using namespace std;

int square(int x);
float square(float x);

int main() {
    cout<<square(3);
    cout<<square(3.14);

    return 0;
}

int square(int x) {
    cout<<"\nINT version called\n";
    return x*x;
}

float square(float x) {
    cout<<"\nFLOAT version called\n";
    return x*x;
}

我试图用双一替换函数的浮点版本,然后它开始工作。这里有什么问题? 3.14不能算float吗?

错误:重载 'square(double)' 的调用不明确
注意:候选人是:
注意: int square(int)
注意:float square(float)

【问题讨论】:

  • 转换为 (float) 或在您的文字 (3.14f) 中使用 f 如果您愿意。我建议使用double,因为它具有更高的精度,并且它是here 中提到的默认浮点数。

标签: c++ overloading


【解决方案1】:

C++ 中的浮点字面量是double 类型。从doubleintfloat 的转换没有定义顺序,因此您的调用不明确。

如果要调用 float 函数,请使用 float 字面量调用它:

cout<<square(3.14f);
//note the f here^

【讨论】:

    【解决方案2】:

    3.14 被编译器视为双精度数。它没有找到带有双参数的函数,并且如果它应该将双精度转换为 int 或浮点数感到困惑。因此请尝试下面的代码或在函数声明中使用双精度。

     cout<<square(3.14f);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-25
      • 2018-04-19
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      相关资源
      最近更新 更多