本文介绍了使用float给出“对重载函数的调用是不明确的”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重载函数 add(),但是当我使用 float 数据类型时,错误。然而,当我把它改为 double ,那么它的工作正常。为什么 float 导致错误?



代码是:

  #include< iostream> 
using namespace std;
class students {
private:
int i;
float f

public:
void add(int b){
i = b;
cout<< First Int:<<一世;
}
void add(float c){
f = c;
cout<< Second Int:<< F;
}

};

int main(){
students obj;
obj.add(9);
obj.add(5.5);
}

错误:

 在函数'int main()':
[错误]调用重载的'add(double)'是不明确的
[注意]候选是:
[注意] void students :: add(int)
[注意] void students :: add(float)
c> double ,但是没有一个你的函数需要一个 double 参数。因此,编译器对是否使用 int 参数或者使用 float 参数调用函数感到困惑。



这就是为什么当你改变函数有一个 double 参数,错误不再来了,因为现在有一个函数可以接受 double 参数,因此有歧义。



您也可以通过调用

  obj.add ; 

在数字后添加 f



§2.13.4



(对不起,发布所有的,但你可以了解更多关于 float 以这种方式)


I'm overloading the function add(), but when I used the float datatype it is showing an error. However, when I change it to double, then it's working fine. Why is float causing the error?

Code is:

#include <iostream>
using namespace std;
class students{
    private:
        int i;
        float f;

    public:
        void add(int b){
            i=b;
            cout << "First Int: " << i;
        }
        void add(float c){
            f=c;
            cout << "Second Int: " << f;
        }

};

int main(){
    students obj;
    obj.add(9);
    obj.add(5.5);
}

Errors:

In function 'int main()':
[Error] call of overloaded 'add(double)' is ambiguous
[Note] candidates are:
[Note] void students::add(int)
[Note] void students::add(float)
解决方案

5.5 is a double, but none of your functions take a double argument. So, the compiler gets confused on whether to call the function with the int parameter, or the function with the float parameter. So, you get a an error saying it is ambiguous.

That is why when you changed the function to have a double parameter, the error no longer came, because now there is a function which can take a double argument, and thus there is ambiguity there.

You can also fix the problem by calling the function as

obj.add(5.5f);

Adding the f after a number makes it to a float.

Let's look at the C++ Standard

§ 2.13.4

( Sorry for posting all of it, but you can learn more about floats this way )

这篇关于使用float给出“对重载函数的调用是不明确的”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:21