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

转载于:https://juejin.im/post/5c8a02f05188257ddb6b05c2

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值