()是调用了类型的构造函数初始化,对于内置类型来说,编译器有默认的构造函数,类似这样:
struct int {
int (const int&);
int (const double&);
...
four bytes data;
};
题主的变量c的初始化,就是调用了其中的一个构造函数(double),所以不会出现警告。
而 {}初始化的方法,仅被最新的C++11标准支持,有个专门的术语:initializer-list,题主可以去查查资料。
这种方法没有使用构造函数,所以凡是能导致精度降低、范围变窄等等的初始化情况,统称为 narrowing conversion,编译器都会警告,narrowing conversion 具体的情况有:
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.
{ } 用于 函数体、复合语句、结构体和数组的初始化
( ) 用于 函数头、函数调用、 各种选择 分支 循环 的条件 、c++变量初始化
懂了吧
在c++中 int 相当于类 。 c(ld) 调用了 数据类型构造函数的 所以是 用()
而{} 表示语言块。 一个{} 表示这些是一块的。
C++还能用花括号初始化?没见过。
int a{ 0 }; 这样初始化是可以的呀,可能是c++11的新特性