c ++中这种初始化有什么区别;
int a = 0;
int a{};
int ();
为什么这段代码int a{3.14}
让我犯了错误,但是这一个a = 3.14
或者这个int a(3.14)
没有
答案 0 :(得分: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
答案 1 :(得分: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:
缩小转化次数
list-initialization限制允许的隐式转换 禁止以下内容:
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是一个常量表达式,其值可以精确存储 目标类型
我希望这个答案有用
答案 2 :(得分: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;
答案 3 :(得分:1)
这两行是等价的
int i = 42;
int j(42);
至于支持初始化,它是C ++ 11 Standard中出现的C ++特性。因此,它不必与C标准兼容,因此它具有更严格的类型安全保证。也就是说,它禁止隐式缩小转换。
int i{ 42 };
int j{ 3.14 }; // fails to compile
int k{ static_cast<int>(2.71) }; // fine
希望有所帮助。如果您需要更多信息,请与我们联系。