18-初始化列表

東閣堂主發表於2019-02-25

寫在前面

初始化列表,旨在初始化的時候為屬性賦值
複製程式碼

碼上建功

//先看一個最基本的建構函式,帶初始化屬性列表的
struct Person {
    int m_age;
    int m_height;

    Person() {
        this->m_age = 10;     //初始化賦值,只能用this獲得屬性,this類似於OC中的self
        this->m_height = 20;
    }
    void display() {
        cout << "m_age is " << this->m_age << endl;
        cout << "m_height is " << this->m_height << endl;
    }
};
執行一下
Person person;
person.display();
看下列印結果:
m_age is 10
m_height is 20

//初始化的時候給屬性賦值
struct Person {
    int m_age;
    int m_height;
    // 初始化列表 :m_age(age), m_height(height)
    //用一個冒號隔開,前面是需要傳入的引數,後面是要賦值的屬性
    Person(int age, int height) :m_height(height), m_age(age)   {
     //對屬性進行一些加工操作
    }
    void display() {
        cout << "m_age is " << this->m_age << endl;
        cout << "m_height is " << this->m_height << endl;
    }
};
使用
Person person2(15, 25);
person2.display();
列印結果
m_age is 15
m_height is 25

當然在初始化的時候也可以通過函式呼叫返回初始化列表的值

int myAge() {
    cout << "myAge()" << endl;
    return 30;
}

int myHeight() {
    cout << "myHeight()" << endl;
    return 180;
}
struct Person {
    int m_age;
    int m_height;
    // 初始化列表 :m_age(age), m_height(height)
    //用一個冒號隔開,前面是需要傳入的引數,後面是要賦值的屬性
    Person():m_height(myHeight()), m_age(myAge()) {
    
    }
    void display() {
        cout << "m_age is " << this->m_age << endl;
        cout << "m_height is " << this->m_height << endl;
    }
};
呼叫
Person person;
person.display();
列印結果:
myAge()
myHeight()
m_age is 30
m_height is 180

當然你也可以這樣來初始化
struct Person {
    int m_age;
    int m_height;

    Person(int age, int height) {
     cout << "Person(int age, int height) " << this << endl;
     this->m_age = age;
     this->m_height = height;
     }

    void display() {
        cout << "m_age is " << this->m_age << endl;
        cout << "m_height is " << this->m_height << endl;
    }
};
呼叫
Person person2(15, 25);
person2.display();
列印
m_age is 15
m_height is 25

複製程式碼

多個初始化列表方法時

struct Person {
    int m_age;
    int m_height;

    Person() :Person(0, 0) { }
    Person(int age, int height) :m_age(age), m_height(height) { }

    void display() {
        cout << "m_age is " << this->m_age << endl;
        cout << "m_height is " << this->m_height << endl;
    }
};
呼叫:
Person person;
person.display();
Person person2(15, 25);
person2.display();
列印結果:
m_age is 0
m_height is 0
m_age is 15
m_height is 25

複製程式碼

如果函式宣告和實現是分離的

struct Person {
    int m_age;
    int m_height;
    // 預設引數只能寫在函式的宣告中
    Person(int age = 0, int height = 0);
};

// 建構函式的初始化列表只能寫在實現中
Person::Person(int age, int height) :m_age(age), m_height(height) {
    
}
呼叫
Person person;
person.display();
Person person2(10);
person2.display();
Person person3(20, 180);
person3.display();
列印結果:
m_age is 0
m_height is 0
m_age is 10
m_height is 0
m_age is 20
m_height is 180
複製程式碼

裝逼一下

一種便捷的初始化成員變數的方式 
只能用在建構函式中 
初始化順序只跟成員變數的宣告順序有關
◼ 如果函式宣告和實現是分離的 
初始化列表只能寫在函式的實現中 
預設引數只能寫在函式的宣告中
 
複製程式碼

完整程式碼demo,請移步GitHub:DDGLearningCpp

相關文章