为什么`bool b = 2`工作良好,但`bool b = {2}`产生缩小转换的警告? [英] Why does `bool b = 2` work well but `bool b = {2}` yield a warning of narrowing conversion?

查看:163
本文介绍了为什么`bool b = 2`工作良好,但`bool b = {2}`产生缩小转换的警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using the {} initializer in C++11 to initialize bool b = {2} yields the following warning message:

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

c $ c> bool b = 2 没有这样的问题。

However, using the old style bool b = 2 has no such problem. What is the reason behind this?

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

Update: I compiled the code using g++ -std=c++11 and it gave me the warning. If I add the option -pedantic-errors, the warning becomes an error.

推荐答案

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

Narrowing a data type in an initialization-list makes your c++11 program ill formed, in this situation the compiler can either give a warning or keep going.

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

Interestingly enough you can actually change it to bool b = {1} and there is no warning, I'm assuming because the value of a bool is guaranteed to convert to 0 and 1 in integral types.

以下是确认错误的标准报价。

Here is a standard quote confirming the error.


缩小转换是一个隐式转换

- 从浮点类型到整数类型, br>
- 从long double到double或float,或从double到float,除非源是常量表达式,转换后的实际值在可以表示的值的范围内(即使它不能正确表示)或

- 从整数类型或无范围的枚举类型转换为浮点类型,除非源是常量表达式,转换后的实际值将适合目标类型,将在转换回原始类型时产生原始值,或

- 从整数类型或无范围的枚举类型转换为无法表示原始类型的所有值的整数类型,除非源是常量表达式和转换后的实际值将适合目标类型,并且在转换回原始类型时将生成原始值。

如上所示,不允许在顶层执行此类转换list-initializations

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

这篇关于为什么`bool b = 2`工作良好,但`bool b = {2}`产生缩小转换的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆