问题
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