18-初始化列表

寫在前面

初始化列表,旨在初始化的時候爲屬性賦值
複製代碼

碼上建功

//先看一個最基本的構造函數,帶初始化屬性列表的
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:DDGLearningCppgit

相關文章
相關標籤/搜索