在C++11之前的版本,初始化是一个没有被统一的写法,有时候用小括号,有时候用大括号,有时候还用赋值号,在学习C语言的时候就深有体会,在c++11中就统一了初始化的形式——“{ }”,直接在对象名后面跟大括号,并在大括号中写入需要初始化的值,并用逗号隔开。甚至类构造函数的初始化列表也可以用“{}”大括号,比如:
int values[] {1,2,3,4};
vector<int> v {1,2,3,4};
complex<double> c{3.0,4.0};
#include <iostream>
#include <string>
using namespace std;
struct Test
{
int a = 1;
string str1 = "Hello C++11";
//string str2("error");
string str3{"Hello fast initialization"};
};
int main()
{
Test t;
cout << t.str1 << endl;
cout << t.str3 << endl;
}