C++ 中的初始化

问题描述

C++中直接初始化和统一初始化有什么区别?

写作有什么区别

int a{5}; // Uniform

int a(5); // Direct

解决方法

在这个特定的例子中,由于选择的类型和值没有区别:int5

在其他一些情况下,初始化的含义取决于我们使用的是 {} 还是 ()。当我们使用括号时,我们是说我们提供的值将用于构造对象,进行计算。当我们使用花括号时,我们是说(如果可能)我们想要列表初始化对象;如果无法列出初始化对象,则对象将通过其他方式进行初始化。

例如

// a has one element,string "foo"
vector<string> a{"foo"};
// error,cannot construct a vector from a string literal
vector<string> b("foo");
// c has 21 default initialized elements
vector<string> c{21};
// d has 21 elements with value "foo"
vector<string> d{21,"foo"};

对于内置类型,例如 int{} 将具有另一个功能:

double d = 3.14;
int i = 0;
i = {d};
// error: narrowing conversion of ‘d’ from ‘double’ to ‘int’

有关详细信息,您可以查看 cppreference.com - Initialization