warning: narrowing conversion of ‘2’ from ‘int’ to ‘bool’ inside { } [-Wnarrowing]
但是,使用旧式bool b = 2没有这样的问题.这背后的原因是什么?
更新:我使用g -std = c 11编译了代码,它给了我警告.如果我添加选项-pedantic-errors,则警告将成为错误.
解决方法
有趣的是,你实际上可以将它改为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