gpt4 book ai didi

c++ - 为什么 `bool b = 2` 工作正常但 `bool b = {2}` 会产生缩小转换的警告?

转载 作者:可可西里 更新时间:2023-11-01 18:25:34 24 4
gpt4 key购买 nike

使用 C++11 中的 {} 初始化程序初始化 bool b = {2} 会产生以下警告消息:

warning: narrowing conversion of ‘2’ from ‘int’ to ‘bool’ inside { } [-Wnarrowing]

但是,使用老式的bool b = 2 没有这个问题。这背后的原因是什么?


更新:我使用 g++ -std=c++11 编译代码,它给了我警告。如果我添加选项 -pedantic-errors,则警告变为错误。

最佳答案

缩小初始化列表中的数据类型会使您的 C++11 程序格式错误,在这种情况下,编译器可以发出警告或继续运行。

有趣的是,您实际上可以将其更改为 bool b = {1} 并且没有警告,我假设是因为 bool 的值保证转换为整数中的 0 和 1类型。

这是确认错误的标准报价。

A narrowing conversion is 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 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.
As indicated above, such conversions are not allowed at the top level in list-initializations

关于c++ - 为什么 `bool b = 2` 工作正常但 `bool b = {2}` 会产生缩小转换的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19737929/

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