初始化列表有繼承時,須要注意下父類的初始化構造參數。
複製代碼
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:DDGLearningCppgit