函数重载如何处理 double 和 float [英] How function overloading works with double and float

查看:119
本文介绍了函数重载如何处理 double 和 float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个重载方法

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

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

当我调用 Sum(5.5, 5.5) 时,会调用具有双返回类型的方法.我的问题是为什么调用具有双返回类型的方法,为什么不调用具有浮点返回类型的方法.编译器如何决定应该调用哪个方法.

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.

推荐答案

因为 5.5 等浮点字面量在 C++<中具有 double 类型 默认.这就是为什么当您将 double 文字 传递给重载函数时,它会调用该函数的接受双类型参数的版本.

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.

如果您想覆盖此默认行为,您需要使用后缀符号,例如 f 来让编译器知道文字具有哪种类型.例如,您需要传递 Sum(5.5f, 5.5f) 而不是 Sum(5.5, 5.5) 以避免默认行为.

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.

这篇关于函数重载如何处理 double 和 float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆