(1)子对象的概念:若派生类A1的数据成员中包含基类A的对象a,则a为派生类A1的子对象
(2)含子对象的派生类的构造函数的执行顺序是:
①调用基类构造函数,对基类数据成员初始化
②调用子对象构造函数,对子对象数据成员初始化
③执行派生类构造函数本身,对派生类数据成员初始化
(3)含子对象的派生类的构造函数的一般形式:
派生类构造函数名(总参数表):基类构造函数名(参数表),子对象名(参数表){派生类中新增数据成员初始化语句}
【代码实例】下面正确运行
#include "bits/stdc++.h"
#include<iostream>
using namespace std;class Student{ //基类 public:Student(int n,string nam){num=n;name=nam;}void display(){cout<<"num:"<<num<<endl<<"name:"<<name<<endl;}protected:int num;string name;}; class Student1:public Student{ //派生类 public:Student1(int n,string nam,int n1,string nam1,int a,string ad):Student(n,nam),monitor(n1,nam1){ //【核】含子对象的派生类构造函数写法 age=a;addr=ad;}void show(){cout<<"This student is:"<<endl;display();cout<<"age:"<<age<<endl;cout<<"address:"<<addr<<endl<<endl;}void show_monitor(){cout<<endl<<"Class monitor is:"<<endl;monitor.display();}private:Student monitor; //子对象 int age;string addr;
};int main(){Student1 stud1(10010,"Wang_li",10001,"Li_sun",19,"115北京,上海路"); stud1.show();stud1.show_monitor(); //输出子对象的数据 return 0;
}