()是呼叫了型別的建構函式初始化,對於內建型別來說,編譯器有預設的建構函式,類似這樣: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.
()是呼叫了型別的建構函式初始化,對於內建型別來說,編譯器有預設的建構函式,類似這樣: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.