美文网首页
19-父类的构造函数

19-父类的构造函数

作者: _东阁堂主_ | 来源:发表于2019-03-14 15:32 被阅读0次

写在前面

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

码上建功

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

相关文章

  • 19-父类的构造函数

    写在前面 码上建功 来看下析构函数 完整代码demo,请移步GitHub:DDGLearningCpp

  • C++ 从入门到放弃 (Day-07)

    父类的构造函数 ◼ 子类的构造函数默认会调用父类的无参构造函数◼ 如果子类的构造函数显式地调用了父类的有参构造函数...

  • Java基础篇

    父类子类构造函数 子类的构造函数会隐式调用父类的无参构造函数,子类若想调用父类的构造函数需在子类的构造函数的第一行...

  • Java面向对象

    1、子类实例化时会默认调用父类无参构造函数,如果父类没有无参构造函数,则需要子类构造函数显示调用父类有参构造函数 ...

  • 面向对象继承的方式

    创建父类 原型链继承:将父类的实例作为子类的原型 借用构造函数继承:在子类型构造函数的内部调用父类的构造函数 组合...

  • 继承中执行顺序讨论

    继承中,子父类的构造函数(构造函数不被继承)1.子类必须调用父类的构造函数(构造函数不被继承)(1)如果没有写调用...

  • 关于构造函数

    父类有参构造函数的作用 子类不能继承父类的构造函数 子类继承父类后,如果想要初始化,必须保证父类已经被构造,此时就...

  • super()

    访问父类的构造函数:可以使用 super() 函数访问父类的构造函数,从而委托父类完成一些初始化的工作 访问父类的...

  • 面向对象(六)-派生类的构造函数

    派生类的构造函数 语法 如果不显式声明调用父类的无参构造函数(base()),那么默认会调用父类的无参构造函数。 ...

  • static代码块、构造代码块、构造函数以及Java类初始化顺序

    顺序:父类静态块-->子类静态块--> main方法-->父类构造代码块 -->父类构造函数-->子类构造代码块-...

网友评论

      本文标题:19-父类的构造函数

      本文链接:https://www.haomeiwen.com/subject/yffcmqtx.html