为什么可以使用从 double 到 float 的隐式转换?

Why Implicit Cast from double to float available?

在 C++ 中我们可以这样写

float f = 3.55;

这是一个合法的声明,而实数数字的类型是双精度,我们将把双精度存储到浮点数中。它本质上意味着将 8 个字节存储为 4 个字节(可能的数据丢失)?我的问题是当我写

long l = 333; 
int y = l;

我得到一个错误,因为 long 值被转换为 int 值(可能丢失数据)。但是为什么我在以浮点数(4 字节)存储 8 字节双精度实数时没有遇到问题?

您的示例没有错误,应该可以编译。

当您将较大的整数类型分配给较小的整数类型(或执行任何不符合提升质量的转换)时,会发生整数转换,精度可能会降低丢失。

类似地,当您将一种浮点类型分配给另一种浮点类型时,会发生浮点转换;结果要么是相同的值,要么是接近它的值,除非源值超出目标类型的范围。

来自 §4 标准转换 [conv] C++11:

Standard conversions are implicit conversions with built-in meaning. Clause 4 enumerates the full set of such conversions. A standard conversion sequence is a sequence of standard conversions in the following order:

...

Zero or one conversion from the following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.

因此,两种数字类型之间的转换是隐式允许的,因为如果小心使用它也是有意义的。例如,当您从 P(int)、R(float) 和 T(int);

计算 Amount(int) 时

以及来自 §4.8 浮点数转换 [conv.double],

  • A prvalue of floating point type can be converted to a prvalue of another floating point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values. Otherwise, the behavior is undefined.
  • The conversions allowed as floating point promotions are excluded from the set of floating point conversions.

似乎 doublefloat 的转换是由兼容的 C++ 编译器隐式执行的。 (以可能失去精度为代价)