C++ 11前的初始化方法
- 小括號初始化方法
int a = int(5)
string s = string("hello")
- 賦值初始化
int a = 3;
string str = "hello";
- 大括號初始化(POD聚合)
int arr[2] = {0,1};
- 構造函數初始化
class test{
test(int var1,int var2):a(var1),b(var2){};
private:
int a;
int b;
};
並不是每種類型都有四種初始化方法,具體需要自己查詢。
C++ 11 統一初始化方法
變量,數組,STL容器,類的構造的初始化都可以使用{}方法
class test{
int a ,b,c[4];
int *d = new int[3]{1,2,3,4};//C++ 11提供的獨有的初始化方式
vector<int> vec = {1,2,3}; //c++ 11 獨有的
map<string, int> _map = {{"hello",1},{"world",2}};//c++ 11 獨有的
public:
test(int i ,int j):a(i),b(j),c{2,3,4,2}{};
};
int main(int argc, const char * argv[])
{
test t{1,2};//初始化test類
return 0;
}
