C++中直接初始化和统一初始化有什么区别?
写和写有什么区别
int a{5}; // Uniform
和
int a(5); // Direct
C++中直接初始化和统一初始化有什么区别?
写和写有什么区别
int a{5}; // Uniform
和
int a(5); // Direct
在此特定示例中,由于选择的类型和值:int
和5
.
在其他一些情况下,初始化的含义取决于我们是否使用{}
或()
。当我们使用括号时,我们是说我们提供的值将用于构造对象,进行计算。当我们使用花括号时,我们是说(如果可能的话)我们想要列出初始化对象;如果无法列出初始化对象,则将通过其他方式初始化该对象。
例如
// 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 - 初始化