【发布时间】:2019-08-01 08:30:40
【问题描述】:
()和{}在构造对象时有什么区别?
我认为 {} 应该只支持 initializer_list 或数组,但是当我在 snip 下运行时,我感到困惑。
#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;
}
statement1 是对的,因为() 是构造对象的基本语法。
我预计statement2 会编译失败。我认为{} 只能用于数组或initializer_list 类型。但实际结果编译完美,没有错误。
我错过了什么?
【问题讨论】:
-
你错过了统一初始化,如果你没听说过你应该搜索它,它是c++11中的一件大事
-
我个人建议避免使用它:
std::vector<int> v{10, 12}- 你认为它会产生什么?有了std::vector<int> v(10, 12)和std::vector<int> v({10, 12}),一切都变得更加清晰......
标签: c++ c++11 initialization