gpt4 book ai didi

c++ - C++中缩小和截断之间的区别?

转载 作者:行者123 更新时间:2023-12-01 14:03:46 25 4
gpt4 key购买 nike

我一直在读一本书(C++ 编程语言 Stroustrup 第 4 版)。
与初始化相关的部分中给出的示例如下:

void f(double d, int i)
{
int a{ d }; // error : possible truncation
char b{ i }; // error : possible narrowing
}

截断和缩小之间究竟有什么区别?

最佳答案

缩小转换基本上是任何可能导致信息丢失的转换。严格来说,一个 narrowing conversion是 :

an implicit conversion

  • from a floating-point type to an integer type, or
  • from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or
  • from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or
  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type, or
  • from a pointer type or a pointer-to-member type to bool.

请注意,这意味着您发布的两个转换都在缩小转换范围。 int a{ d };是第一种情况和 char b{ i };是第四个。
截断仅在浮点类型和整数类型之间转换时发生。它通常是指丢失的浮点数的小数部分 ( source )。这意味着截断是缩小转换的子集。

关于c++ - C++中缩小和截断之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61106262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com