C++11 初始化

來源:互聯網
上載者:User

標籤:ini   test   data   導致   int   添加   pause   ring   錯誤   

C++11 初始化

統一初始化文法
        C++11新添加初始化列表 std::initializer_list<>類型,可以通過{}文法來構造初始化列表 。初始化列表是常數;一旦被建立,其成員均不能被改變,成員中的資料也不能夠被變動。函數能夠使用初始化列表作為參數。
        在引入C++ 11之前,有各種不同的初始化文法。在C++ 11中,仍可以使用這些初始化文法,但也可以選擇使用新引入的統一的初始化文法。統一的初始化文法用一對大括弧{}表示。
        std::vector<string> v1 = {"hello", "world", "welcome"};
        std::vector<int> v2 = {0, 3, 8, 1, 4};

 

// 注: vs2012 不支援統一初始化方式{}

 

類內成員初始化

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <vector>#include <map>class Mem{public:    Mem(int i, int j): m(i), n(j) // 初始化列表給m初始化, 可以給const變數賦初值, 以及引用變數賦初值    {        // m = i; 錯誤,不能給const變數賦值        // n = j; 錯誤,不能給引用變數賦值    }    int getM()    {        std::cout << "m: " << m << std::endl;    }    const int m;    int &n;};void mytest(){    int data = 1; // 使用"="初始化非靜態普通成員,也可以 int data{1};    Mem Mem{2, data}; // 對象成員,建立對象時,可以使用{}來調用建構函式 // 注: vs2012 不支援統一初始化方式{}    std::string name("xyz"); // 使用()來調用建構函式    return;}int main(){    mytest();    system("pause");    return 0;}

 

 

列表初始化
C++11引入了一個新的初始化方式,稱為初始化列表(List Initialize),具體的初始化方式如下:

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <vector>#include <map>class Person{public:    std::string name;    int age;};void mytest(){    int a[] = {4,5,6};    int b[]{1,3,5}; // 注: vs2012 不支援    int i = {1};    int j{3}; // 注: vs2012 不支援    // 初始化列表可以用於初始化結構體類型    Person p1 = {"Frank", 25};    std::vector<int> ivec1(3,4);    // 其他一些不方便初始化的地方使用,比如std<vector>的初始化,如果不使用這種方式,只能用建構函式來初始化,難以達到效果    std::vector<int> ivec2 = {5,5,5}; // 注: vs2012 不支援    std::vector<int> ivec3 = {1,2,3,4,5}; // 注: vs2012 不支援    return;}int main(){    mytest();    system("pause");    return 0;}

 

防止類型收窄
類型收窄指的是導致資料內容發生變化或者精度丟失的隱式類型轉換。使用列表初始化可以防止類型收窄。

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>#include <vector>#include <map>void mytest(){    const int x = 1024;    const int y = 10;    char a = x; // 收窄,但可以通過編譯    char *b = new char(1024); // 收窄,但可以通過編譯    char c = {x}; // err,收窄,無法通過編譯    char d = {y}; // 可以通過編譯    unsigned char e{-1}; // err,收窄,無法通過編譯    float f{7}; // 可以通過編譯    int g{2.0f}; // err,收窄,無法通過編譯    float * h = new float{1e48}; // err,收窄,無法通過編譯    float i = 1.21; // 可以通過編譯    return;}int main(){    mytest();    system("pause");    return 0;}

 

C++11 初始化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.