子类继承父类后,当创建子类对象,也会调用父类的构造函数

问题:父类和子类的构造和析构顺序是谁先谁后?

  • 如果是单继承 ```cpp

    include

    using namespace std; class Person{ public: Person(){
    1. cout << "Person构造函数的调用" << endl;
    } ~Person(){
    1. cout << "Person析构函数的调用" << endl;
    } };

class Student:public Person{ public: Student(){ cout << “Student构造函数的调用” << endl; } ~Student(){ cout << “Student析构函数的调用” << endl; } }; int main(){ Student student; return 0; }

  1. ![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)
  2. 会先调用父类的构造函数,然后再调用子类的构造函数<br />**没有父亲,哪里来的儿子**<br />**<br />**<br />**
  3. - **如果是多继承**
  4. ```cpp
  5. #include <iostream>
  6. using namespace std;
  7. class Person{
  8. public:
  9. Person(){
  10. cout << "Person构造函数的调用" << endl;
  11. }
  12. ~Person(){
  13. cout << "Person析构函数的调用" << endl;
  14. }
  15. };
  16. class Worker{
  17. public:
  18. Worker(){
  19. cout << "Worker构造函数的调用" << endl;
  20. }
  21. ~Worker(){
  22. cout << "Worker析构函数的调用" << endl;
  23. }
  24. };
  25. class Student:public Worker,public Person{
  26. public:
  27. Student(){
  28. cout << "Student构造函数的调用" << endl;
  29. }
  30. ~Student(){
  31. cout << "Student析构函数的调用" << endl;
  32. }
  33. };
  34. int main(){
  35. Student student;
  36. return 0;
  37. }

image.png

单继承会依据继承顺序,来调用父类的构造函数,比如这里会依次调用Worker, Person和 Student的构造函数