【C++】 用花括号初始化和用括号初始化有什么区别?

本文深入探讨了C++中使用不同语法进行类型转换的特点,解析了为什么使用圆括号()和花括号{}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比如下面这个问题

long double ld=3.1415926536;
int a{ld},b={ld}; //错误,转换未执行,因为存在丢失信息的危险
int c(ld),d=(ld); //正确,转化执行,且确实丢失了部分值

为什么会提示 “a”本地函数定义是非法的,而c,d却又没问题呢?这跟a用花括号定义有什么联系?

()是调用了类型的构造函数初始化,对于内置类型来说,编译器有默认的构造函数,类似这样:
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.

转自:https://zhidao.baidu.com/question/1668775549685301747.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值