C++变量初始化的几种方式

发布时间 2023-07-12 14:35:49作者: para_dise

有几种初始化的方式,主要是关于{}初始化,存在一些点需要记住。

 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 
11     cout<<"x1="<<x1<<endl;
12     cout<<"x2="<<x2<<endl;
13     cout<<"x3="<<x3<<endl;
14     cout<<"x4="<<x4<<endl;
15 
16     return 0;
17 }

结果输出如下代码:

x1=3
x2=3
x3=3
x4=3

Process returned 0 (0x0)   execution time : 0.034 s
Press any key to continue.

 看起来四种方法都很合适,但是,第三、四种方法编译器会分别给出警告:

||warning: narrowing conversion of 'pi' from 'double' to 'int' [-Wnarrowing]|
||warning: narrowing conversion of 'pi' from 'double' to 'int' [-Wnarrowing]|
||=== 构建 finished: 0 error(s), 2 warning(s) (0 分, 0 秒) ===|

 四种方式相对而言,使用花括号的方法会更安全(但是并没有像书中说的那样报错)