gpt4 book ai didi

c++ - 为什么列表初始化允许从 double 值转换为浮点值?

转载 作者:可可西里 更新时间:2023-11-01 15:09:55 28 4
gpt4 key购买 nike

列表初始化({...} 语法)不允许缩小转换。例如,尝试使用 3.14f 列表初始化 int i 会出现编译错误,因为从浮点值到整数的转换正在缩小:

<source>:11:32: error: narrowing conversion of '3.1400001e+0f' from 'float' to 'int' inside { } [-Wnarrowing]
int i{3.14f};
^

话虽如此,为什么可以用 3.14 构造一个double 类型的float f? (从 doublefloat 的转换被认为是缩小的。)执行以下操作:

float f{3.14};

没有编译错误。

最佳答案

在被认为是缩小转换的列表中,适合目标类型的常量表达式是一个异常(exception)。因此,虽然通常 double 到 float 会变窄,但当您的 double 实际上是文字时,这是允许的。

http://coliru.stacked-crooked.com/a/6949f04fa4a8df17


根据我手头的草稿(我认为接近 C++14):

8.5.4 List-initialization
(7.2) A narrowing conversion is an implicit conversion...
...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),

关于c++ - 为什么列表初始化允许从 double 值转换为浮点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48141187/

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