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 }
复制代码

  结果输出如下代码:

1
2
3
4
5
6
7
x1=3
x2=3
x3=3
x4=3
(这里把x5的注释掉了)<br>
Process returned 0 (0x0)   execution time : 0.034 s
Press any key to continue.

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

1
2
|8|warning: narrowing conversion of 'pi' from 'double' to 'int' [-Wnarrowing]|
|9|warning: narrowing conversion of 'pi' from 'double' to 'int' [-Wnarrowing]|<br>|10|error: narrowing conversion of '3.1400000000000001e+0' from 'double' to 'int' [-Wnarrowing]|<br>||=== 构建 finished: 0 error(s), 2 warning(s) (0 分, 0 秒) ===|

结论:

  使用{ }进行列表初始化的时候,如果直接放的是不匹配的数据类型的值,会发生报错

  使用{ }进行列表初始化的时候,如果使用的是不匹配的数据类型的变量(可以类型转换),那么可以通过,但是会给出警告

  使用其他方法,编译器会自动进行强制类型转换且没有提示。

posted @   para_dise  阅读(118)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示