gpt4 book ai didi

c++ - 为什么 const int 适合 char 大括号 init?

转载 作者:行者123 更新时间:2023-12-02 06:16:10 25 4
gpt4 key购买 nike

我认为大括号初始化不允许缩小。但为什么 char 大括号初始化允许使用 int const 呢?

int value1 = 12;
char c1{value1}; // error! no narrowing

const int value2 = 12;
char c2{value2}; // why is this fine?

查看on Godbolt .

最佳答案

const int value2 = 12;

value2 是一个编译时常量。编译器可以轻松(并且必须)证明该值是 12,它恰好在 char 表示的值范围内。

int value1 = 12;

value1 不是编译时常量。变量的值可能会在运行时更改。

标准规则的确切措辞(引用最新草案,强调部分已添加):

[dcl.init.list]/7

A narrowing conversion is an implicit conversion

  • 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.

关于c++ - 为什么 const int 适合 char 大括号 init?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57855180/

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