int and float in function overloading

心已入冬 提交于 2021-01-27 11:42:03

问题


I have two overloaded function like below:

void print(int i) { ... }
void print(float f) { ... }

Its giving me this error for print(1.2);:

error: call of overloaded 'print(double)' is ambiguous 

Can anyone explain me why?


回答1:


1.2 is a double literal not a float.

So the compiler requires an explicit disambiguation.

1.2f would work as that is a float literal.




回答2:


1.2 is a double literal, making the function you're trying to call ambiguous - a double can just as easily be truncated to a float or to an int. Using a float literal (1.2f) or explicitly casting it would solve the problem.




回答3:


It is interpreting 1.2 as a double. Casting it to a float will solve the problem.

print( float(1.2) );



来源:https://stackoverflow.com/questions/34208397/int-and-float-in-function-overloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!