19-父类的构造函数

写在前面

初始化列表有继承时,需要注意下父类的初始化构造参数。

码上建功

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 7,890评论 2 9
  • 支付宝集成 一、相关文档 1. SDK集成流程 2. SDK下载地址 二、SDK集成流程 1. 2. 3. 自己制...
    不要虚度美好的时光阅读 1,014评论 0 0
  • 01、人生没有绝对的安稳,既然我们都是过客,就该携一颗从容淡泊的心,走好脚下的路。 02、人生虽然艰难,但是如果你...
    不倒翁007阅读 689评论 0 0
  • 今天。走在昏暗的灯下的路上。 突然发现21岁的我,自己是一个平凡得不能再平凡的女孩儿。 我既没有那种一眼看上去就喜...
    蓝蔚公子阅读 1,423评论 2 1