1. 程式人生 > >C++11 初始化

C++11 初始化

blog 發生 [] person 精度 丟失 ios turn warn

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 初始化