c++---派生类的构造函数和析构函数

    xiaoxiao2021-03-25  233

    派生类的构造函数

    基类的构造函数是不能继承的,在声明派生类时,派生类并没有把基类的构造函数继承过来,因此,对继承过来的数据成员的初始化工作也要由派生类的构造函数来承担。所以设计派生类的构造函数,不仅对新增的成员进行初始化,还要对继承的成员进行初始化。希望在执行派生类的构造函数时,同时对新增的成员和继承的成员同时初始化。解决的思路就是,在执行派生类的构造函数时候,调用基类的构造函数。

    简单派生的构造函数

    简单的派生类只有一个基类,而且只有一级派生。

    派生类的构造函数名(总参数列表):基类构造函数名(参数列表)

    {派生类新增的数据成员初始化语句}

    简单派生的例子

    #include<iostream> using namespace std; class Student { public: Student(int n, string na):number(n),name(na){} void display() { cout<<"The number: "<<number<<endl; cout<<"The name: "<<name<<endl; } ~Student(){} protected: //保护成员是为了让派生类输出成员 int number; string name; }; class Student1: public Student { public: Student1(int n, string na,int ag,string add):Student(n,na) //派生类的构造函数 { age = ag; addr =add; } ~Student1(){} void display1() { cout<<"The number: "<<number<<endl; cout<<"The name: "<<name<<endl; cout<<"The age: "<<age<<endl; cout<<"The addr: "<<addr<<endl; } private: int age; string addr; }; int main() { Student1 stu1(10286,"yqq",27,"beijing"); stu1.display1(); return 0; }

    有子对象的构造函数

     类的数据成员中包含着类的对象,如可以在声明一个类时,包含这样的数据成员:

    Student s1; //Student已经声明的类,s1是Student的对象这个时候,s1 就是对象中内嵌的对象,称作子对象。

    派生类构造函数的任务应该包括3部分:

    (1)对基类数据成员初始化

    (2)对子对象数据成员初始化

     (3)对派生类数据成员初始化

    派生类构造函数的一般形式:

    派生类构造函数名(总参数列表):基类构造函数名(参数列表),子对象名(参数列表)

    {派生类中新增数据成员初始化语句}

    有子对象的构造函数举例

    #include<iostream> using namespace std; class Student { public: Student(int n, string na):number(n),name(na){} void display() { cout<<"The number: "<<number<<endl; cout<<"The name: "<<name<<endl; } ~Student(){} protected: int number; string name; }; class Student1: public Student { public: Student1(int n, string na,int nl, string nal,int ag,string add ):Student(n,na),monitor(nl,nal) { age = ag; addr =add; } ~Student1(){} void display1() { cout<<"The number: "<<number<<endl; cout<<"The name: "<<name<<endl; cout<<"The age: "<<age<<endl; cout<<"The addr: "<<addr<<endl; } void display2() { cout<<"The monitor is:"<<endl; monitor.display(); } private: Student monitor; //定义子对象(班长) int age; string addr; }; int main() { Student1 stu1(10286,"yqq",100,"ads",27,"beijing"); stu1.display1(); stu1.display2(); return 0; }

     执行构造函数的顺序:

    (1)调用基类的构造函数,对基类成员初始化。

    (2)调用子对象构造函数,对子对象数据成员初始化。

    (3)再执行派生类构造函数本身,对派生类数据成员初始化。

    多层派生的构造函数

    转载请注明原文地址: https://ju.6miu.com/read-394.html

    最新回复(0)