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

比如下面这个问题

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

猜你喜欢

转载自blog.csdn.net/u013066730/article/details/86219240