19-父類的建構函式

東閣堂主發表於2019-03-14

寫在前面

初始化列表有繼承時,需要注意下父類的初始化構造引數。
複製程式碼

碼上建功

class Person {
    int m_age;
public:
    //父類的無參建構函式
    Person() {
        cout << "Person()" << endl;
    }
    //父類的有參建構函式
    Person(int age) :m_age(age) {
        cout << "Person(int age)" << endl;
    }
};

class Student : public Person {
    int m_score;
public:
    //子類的無參建構函式
    Student() {
        cout << "Student()" << endl;
    }
    //子類的無參建構函式
    Student(int age, int score) :m_score(score), Person(age) {
        cout << "Student(int age, int score)" << endl;
    }
};
呼叫
Student student;
Student student2(10,30);
列印結果;
Person()
Student()
Person(int age)
Student(int age, int score)
可以看出:
◼ 子類的建構函式預設會呼叫父類的無參建構函式
◼ 如果子類的建構函式顯式地呼叫了父類的有參建構函式,就不會再去預設呼叫父類的無參建構函式


class Person {
    int m_age;
public:
    Person(int age) :m_age(age) {
        cout << "Person(int age)" << endl;
    }
};

class Student : public Person {
    int m_score;
public:
    Student() :Person(0) {

    }
};
◼ 如果父類缺少無參建構函式,子類的建構函式必須顯式呼叫父類的有參建構函式
 
複製程式碼

來看下解構函式

class Person {
    int m_age;
public:
    //父類的無參建構函式
    Person() {
        cout << "Person()" << endl;
    }
    //父類的有參建構函式
    Person(int age) :m_age(age) {
        cout << "Person(int age)" << endl;
    }
    ~Person() {
        cout << "~Person()" << endl;
    }
};

class Student : public Person {
    int m_score;
public:
    //子類的無參建構函式
    Student() {
        cout << "Student()" << endl;
    }
    //子類的無參建構函式
    Student(int age, int score) :m_score(score), Person(age) {
        cout << "Student(int age, int score)" << endl;
    }
    ~Student() {
        cout << "~Student" << endl;
    }
};
呼叫
Student *student = new Student();
delete student;
列印:
~Student
~Person()
構造和析構順序相反,先呼叫子類的解構函式,先呼叫父類的建構函式
複製程式碼

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

相關文章