函数重载如何与 double 和 float 一起工作
How function overloading works with double and float
我有两个重载方法
double Sum(double n1, double n2)
{
return n1 + n2;
}
float Sum(float n1, float n2)
{
return n1 + n2;
}
当我调用 Sum(5.5, 5.5)
时,会调用 double
return 类型的方法。
我的问题是为什么调用double
return类型的方法,而不调用float
return类型的方法?编译器如何决定应该调用哪个方法?
因为 5.5 等浮点文字在 C++ 中的默认类型为 double
。这就是为什么当您将 double literal 传递给重载函数时,它将调用该函数的接受 double 类型参数的版本。
如果您想覆盖此默认行为,您需要使用 后缀符号 例如 f
让编译器知道文字具有哪种类型。例如,您需要传递 Sum(5.5f, 5.5f)
而不是 Sum(5.5, 5.5)
以避免默认行为。
我有两个重载方法
double Sum(double n1, double n2)
{
return n1 + n2;
}
float Sum(float n1, float n2)
{
return n1 + n2;
}
当我调用 Sum(5.5, 5.5)
时,会调用 double
return 类型的方法。
我的问题是为什么调用double
return类型的方法,而不调用float
return类型的方法?编译器如何决定应该调用哪个方法?
因为 5.5 等浮点文字在 C++ 中的默认类型为 double
。这就是为什么当您将 double literal 传递给重载函数时,它将调用该函数的接受 double 类型参数的版本。
如果您想覆盖此默认行为,您需要使用 后缀符号 例如 f
让编译器知道文字具有哪种类型。例如,您需要传递 Sum(5.5f, 5.5f)
而不是 Sum(5.5, 5.5)
以避免默认行为。