How function overloading works with double and float

依然范特西╮ 提交于 2019-12-11 06:16:20

问题


I have two overloaded methods

double Sum(double n1, double n2)
{
     return n1 + n2;
}

float Sum(float n1, float n2)
{
     return n1 + n2;
}

When i call Sum(5.5, 5.5), the method with double return type gets called. My question is why the method with double return type is called, why not method with float return type. How the compiler is deciding that which method should be called.


回答1:


Because, floating-point literals such as 5.5 have the type double in C++ as default. That's why, when you pass a double literal to an overloaded function, it is going to call the version of that function which accepts the double typed parameters.

If you want to override this default behaviour, you need to be using suffix notations such as f to let the compiler know which type does literal have. As an example, you need to be passing Sum(5.5f, 5.5f) instead of Sum(5.5, 5.5) to avoid default behaviour.




回答2:


Because the default type of floating point is double in c++... So when you call function sum(5.5,5.5)... The compiler will go to the function that return type double... If you want to call a float function you should write" f "after the number 5.5.....like sum(5.5f, 5.5f)...or you can initialize two variables as a float type and send them as a parameter to the function....



来源:https://stackoverflow.com/questions/54090448/how-function-overloading-works-with-double-and-float

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