C++初始化int与double的区别

问题描述:

这种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) –

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 

源是一个常数表达式,其值可以完全保存在 目标类型中

我想这个答案将是有益的

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 {...};' –

这就是所谓的列表初始化(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();'变量创建还是函数声明?我的理解是它将是一个函数声明。 –

这两条线是等效

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 

希望有帮助。如果您需要更多信息,请与我们联系。