()
和 {}
构造对象时有什么区别呢?
我认为 {} 只能用于支持 initializer_list
或数组,但当我运行下面的代码片段时感到困惑。
#include <iostream>
using namespace std;
struct S {
int v=0;
S(int l) : v(l) {
}
};
int main()
{
S s1(12); // statement1
S s2{12}; // statement2
cout << s1.v << endl;
cout << s2.v << endl;
}
语句1
正确,因为()
是构建对象的基本语法。
我预计语句2
将编译失败。我认为{}
只能用于数组或initializer_list
类型。但实际结果却可以完美编译而不会出错。
我错在哪里了?
std::vector<int> v{10, 12}
- 你认为它会产生什么结果?使用std::vector<int> v(10, 12)
或std::vector<int> v({10, 12})
更加清晰明了。 - Aconcagua