首页 文章

C中的函数重载 . 不适用于浮点数,使用双[重复]

提问于
浏览
1

这个问题在这里已有答案:

#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;
}

我试图用double替换函数的float版本,然后它开始工作 . 这里有什么问题?不能将3.14视为浮动?

错误:调用重载'square(double)'是模棱两可的注意事项:候选者是:注意:int square(int)注意:float square(float)

2 回答

  • 0

    C中的浮点文字的类型为 double . 从 doubleintfloat 的转化没有定义排序,因此您的通话不明确 .

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

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

    3.14被编译器视为double . 它没有找到带有double参数的函数,如果它应该将double转换为int或float,则会感到困惑 . 因此,请尝试使用下面的代码或在函数声明中使用double .

    cout<<square(3.14f);
    

相关问题