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