在c++;双倍 这类初始化在C++中有什么不同?p> int a = 0; int a{}; int ();

在c++;双倍 这类初始化在C++中有什么不同?p> int a = 0; int a{}; int ();,c++,initialization,clion,C++,Initialization,Clion,为什么此代码inta{3.14}get me错误,但此代码a=3.14或此代码inta(3.14)不a{3.14}将引发错误,因为您没有指定 inta(3.14)//初始值:3.14,您可以使用{}也可以使用intead of()wont,因为您说它是整数 我将向您提供一些解释,希望您能更清楚地了解: // Bog-standard declaration. int a; // WRONG - this declares a function. int a(); //

为什么此代码
inta{3.14}
get me错误,但此代码
a=3.14
或此代码
inta(3.14)
a{3.14}
将引发错误,因为您没有指定

inta(3.14)//初始值:3.14,您可以使用{}也可以使用intead of()
wont,因为您说它是整数

我将向您提供一些解释,希望您能更清楚地了解:

// 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;

这称为列表初始化(C++11):

然而:

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

这两条线是相等的

int i = 42;
int j(42);

关于支撑初始化,它是C++ 11标准中出现的C++特性。因此,它不必与C标准兼容,因此它具有更严格的类型安全保证。也就是说,它禁止隐式缩小转换

int i{ 42 };
int j{ 3.14 }; // fails to compile
int k{ static_cast<int>(2.71) }; // fine
inti{42};
int j{3.14};//未能编译
int k{static_cast(2.71)};//好的
希望有帮助。如果您需要更多信息,请告诉我。

int a=0;和int a(0);在机器生成的代码中没有区别。它们是一样的

以下是在VisualStudio中生成的汇编代码

int a = 10;   // mov dword ptr [a],0Ah  
int b(10);    // mov dword ptr [b],0Ah
但是
inta{}
有点不同,这是因为缩小了转换范围,禁止了一些列表初始化

这些资料来自:

缩小转换范围

列表初始化通过以下方式限制允许的隐式转换 禁止下列行为:

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
source是一个常量表达式,其值可以精确地存储在 目标类型


我希望这个答案会有用

查找Is
intfoo()变量创建还是函数声明?我的理解是,这将是一个函数声明。对于一个只能有一个值的变量,列表初始化是如何工作的?例如
inta={…};int a{…}
conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where