C++ 各种容器初始化问题


C++ 11前的初始化方法
  1. 小括号初始化方法
int a = int(5)

string s = string("hello")

  1. 赋值初始化
int a = 3;
string str = "hello";

  1. 大括号初始化(POD聚合)
int arr[2] = {0,1};
  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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM