Using float gives “call to overloaded function is ambiguous” error
我正在重载函数
代码是:
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) |
这就是为什么当您将函数更改为具有
您也可以通过调用以下函数来解决问题:
1 | obj.add(5.5f); |
在数字后面加上
让我们看一下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.
(很抱歉将其全部发布,但是您可以通过这种方式了解有关