【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的初始化,就是呼叫了其中的一個
而 {}初始化的方法,僅被最新的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
— 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
轉自:https://zhidao.baidu.com/question/1668775549685301747.html