C++变量初始化的几种方式
有几种初始化的方式,主要是关于{ }初始化,存在一些点需要记住。
1 #include <iostream> 2 using namespace std; 3 int main() 4 { 5 double pi=3.2415; 6 int x1=pi; 7 int x2(pi); 8 int x3{pi}; 9 int x4={pi}; 10 int x5={3.14}; 11 cout<<"x1="<<x1<<endl; 12 cout<<"x2="<<x2<<endl; 13 cout<<"x3="<<x3<<endl; 14 cout<<"x4="<<x4<<endl; 15 cout<<"x5="<<x5<<endl; 16 return 0; 17 }
结果输出如下代码:
x1=3 x2=3 x3=3 x4=3 (这里把x5的注释掉了)
Process returned 0 (0x0) execution time : 0.034 s Press any key to continue.
这五种方法里面看起来前四种方法都很合适,但是,第三、四种方法编译器会分别给出警告,第五种方法会报错:
|8|warning: narrowing conversion of 'pi' from 'double' to 'int' [-Wnarrowing]| |9|warning: narrowing conversion of 'pi' from 'double' to 'int' [-Wnarrowing]|
|10|error: narrowing conversion of '3.1400000000000001e+0' from 'double' to 'int' [-Wnarrowing]|
||=== 构建 finished: 0 error(s), 2 warning(s) (0 分, 0 秒) ===|
结论:
使用{ }进行列表初始化的时候,如果直接放的是不匹配的数据类型的值,会发生报错
使用{ }进行列表初始化的时候,如果使用的是不匹配的数据类型的变量(可以类型转换),那么可以通过,但是会给出警告
使用其他方法,编译器会自动进行强制类型转换且没有提示。

浙公网安备 33010602011771号