Using float gives “call to overloaded function is

2019-01-05 05:47发布

This question already has an answer here:

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)

1条回答
地球回转人心会变
2楼-- · 2019-01-05 06:46

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

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.

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

查看更多
登录 后发表回答