写在前面
初始化列表有继承时,需要注意下父类的初始化构造参数。
码上建功
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