在C++中直接初始化和统一初始化有什么区别?
写作有什么区别?
int a{5}; // Uniform和
int a(5); // Direct发布于 2021-08-01 09:45:51
在这个特殊的例子中,由于选择的类型和值没有任何不同: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 -初始化
https://stackoverflow.com/questions/68609060
复制相似问题