子类继承父类后,当创建子类对象,也会调用父类的构造函数
问题:父类和子类的构造和析构顺序是谁先谁后?
- 如果是单继承
```cpp
include
using namespace std; class Person{ public: Person(){
} ~Person(){cout << "Person构造函数的调用" << endl;
} };cout << "Person析构函数的调用" << endl;
class Student:public Person{ public: Student(){ cout << “Student构造函数的调用” << endl; } ~Student(){ cout << “Student析构函数的调用” << endl; } }; int main(){ Student student; return 0; }
![image.png](https://cdn.nlark.com/yuque/0/2021/png/21436600/1623930072953-274dbc5e-6606-46ae-a604-a37ec88469e0.png#align=left&display=inline&height=406&originHeight=541&originWidth=998&size=142244&status=done&style=none&width=749)
会先调用父类的构造函数,然后再调用子类的构造函数<br />**没有父亲,哪里来的儿子**<br />**<br />**<br />**
- **如果是多继承**
```cpp
#include <iostream>
using namespace std;
class Person{
public:
Person(){
cout << "Person构造函数的调用" << endl;
}
~Person(){
cout << "Person析构函数的调用" << endl;
}
};
class Worker{
public:
Worker(){
cout << "Worker构造函数的调用" << endl;
}
~Worker(){
cout << "Worker析构函数的调用" << endl;
}
};
class Student:public Worker,public Person{
public:
Student(){
cout << "Student构造函数的调用" << endl;
}
~Student(){
cout << "Student析构函数的调用" << endl;
}
};
int main(){
Student student;
return 0;
}
单继承会依据继承顺序,来调用父类的构造函数,比如这里会依次调用Worker, Person和 Student的构造函数