2017-07-14 94 views
4

這種C++初始化有什麼區別;C++初始化int與double的區別

int a = 0; 
int a{}; 
int(); 

爲什麼這個代碼int a{3.14}讓我的錯誤,但這個INT a = 3.14或這一個int a(3.14)

+3

查找[縮小轉換(http://en.cppreference.com/w/cpp/language/list_initialization#Narrowing_conversions) –

回答

2

int a = 0;和int a(0);在機器生成的代碼中沒有任何區別。他們是一樣的。

以下是在Visual Studio中生成的彙編代碼

int a = 10; // mov dword ptr [a],0Ah 
int b(10); // mov dword ptr [b],0Ah 

int a{}是因爲收縮轉換,禁止的一點點不同的一些列表初始化

這些都是c++ reference site

縮小轉換範圍

列表初始化由 限制所允許的隱式轉換禁止以下:

conversion from a floating-point type to an integer type 

conversion from a long double to double or to float and conversion from double to float, except where the source is a constant expression 

和從不溢出

conversion from an integer type to a floating-point type, except where the source is a constant expression whose value can be stored 

恰好在目標類型

conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where 

源是一個常數表達式,其值可以完全保存在 目標類型中

我想這個答案將是有益的

1

a{3.14}將拋出一個錯誤,因爲你沒有指定type

int a(3.14) // initial value: 3.14, you could use {} also intead of()不會因爲你說的是整數..

我會給你提供一些解釋,希望對你更清楚:

// Bog-standard declaration. 


    int a; 


// WRONG - this declares a function. 

    int a(); 

// Bog-standard declaration, with constructor arguments. 
// (*) 

    int a(1, 2, 3... args); 

// Bog-standard declaration, with *one* constructor argument 
// (and only if there's a matching, _non-explicit_ constructor). 
// (**) 

    int a = 1; 

// Uses aggregate initialisation, inherited from C. 
// Not always possible; depends on layout of T. 

    int a = {1, 2, 3, 4, 5, 6}; 

// Invoking C++0x initializer-list constructor. 

    int a{1, 2, 3, 4, 5, 6}; 

// This is actually two things. 
// First you create a [nameless] rvalue with three 
// constructor arguments (*), then you copy-construct 
// a [named] T from it (**). 

    int a = T(1, 2, 3); 

// Heap allocation, the result of which gets stored 
// in a pointer. 

    int* a = new T(1, 2, 3); 

// Heap allocation without constructor arguments. 

    int* a = new T; 
+0

如何列表初始化工作的變量只能有一個值?例如'int a = {...}; int a {...};' –

4

這就是所謂的列表初始化(C++ 11):

int foo = 0; // Initialize foo with 0 
int foo{}; // Initialize foo with foo's type (int) default value, which is 0 
int foo(); // Function declaration 

int bar = 5.f; // Initialize bar with 5 (narrowing conversion from floating point) 
int bar{5.f}; // Doesn't compile, because there is a loss of data when casting a float to an int 
int bar(5.f); // Initialize bar with 5 (narrowing conversion from floating point) 

然而:

float f{5}; // Okay, because there is no loss of data when casting an int to a float 
+0

是'int foo();'變量創建還是函數聲明?我的理解是它將是一個函數聲明。 –

1

這兩條線是等效

int i = 42; 
int j(42); 

至於支撐初始化,這是一個C++特性出現C++ 11標準。因此,它不必與C標準兼容,因此它具有更嚴格的類型安全保證。也就是說,它禁止隱含縮小轉換。

int i{ 42 }; 
int j{ 3.14 }; // fails to compile 
int k{ static_cast<int>(2.71) }; // fine 

希望有幫助。如果您需要更多信息,請與我們聯繫。