关于c ++:使用float会导致“对重载函数的调用不明确”错误

Using float gives “call to overloaded function is ambiguous” error

本问题已经有最佳答案,请猛点这里访问。

我正在重载函数add(),但是当我使用float数据类型时,它显示了一个错误。 但是,当我将其更改为double时,它可以正常工作。 为什么float导致错误?

代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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);
}

错误:

1
2
3
4
5
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.5double,但是您的函数均不使用double自变量。 因此,编译器对于是使用int参数调用函数还是使用float参数调用函数感到困惑。 因此,您会收到一个错误消息,说它是模棱两可的。

这就是为什么当您将函数更改为具有double参数时,不再出现错误的原因,因为现在有一个函数可以接受double参数,因此那里存在歧义。

您也可以通过调用以下函数来解决问题:

1
obj.add(5.5f);

在数字后面加上f使其成为浮点数。

让我们看一下C ++标准

第2.13.4节

1 A floating literal consists of an integer part, a decimal point, a
fraction part, an e or E, an optionally signed integer exponent, and
an optional type suffix. The integer and fraction parts both consist
of a sequence of decimal (base ten) digits. Optional separating single
quotes in a digit-sequence are ignored when determining its value. [
Example: The literals 1.602’176’565e-19 and 1.602176565e-19 have the
same value. —end example ] Either the integer part or the fraction
part (not both) can be omitted; either the decimal point or the letter
e (or E ) and the exponent (not both) can be omitted. The integer
part, the optional decimal point and the optional fraction part form
the significant part of the floating literal. The exponent, if
present, indicates the power of 10 by which the significant part is to
be scaled. If the scaled value is in the range of representable values
for its type, the result is the scaled value if representable, else
the larger or smaller representable value nearest the scaled value,
chosen in an implementation-defined manner. The type of a floating
literal is double unless explicitly specified by a suffix. The
suffixes f and F specify float, the suffixes l and L specify long
double. If the scaled value is not in the range of representable
values for its type, the program is ill-formed.

(很抱歉将其全部发布,但是您可以通过这种方式了解有关float的更多信息)