在 C++ 中用 double 初始化 int 之间的区别

differences between initializing int in c++ with double

这种在c++中初始化的区别是什么;

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

为什么这段代码 int a{3.14} 让我出错,但这个 int a = 3.14 或这个 int a(3.14) 没有

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;

它被称为列表初始化 (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

这两行是等价的

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

希望对您有所帮助。如果您需要更多信息,请告诉我。

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:

Narrowing conversions

list-initialization limits the allowed implicit conversions by prohibiting the following:

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

and overflow does not occur

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

exactly in the target type

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

source is a constant expression whose value can be stored exactly in the target type

我希望这个答案有用