#include<iostream>
using namespace std;
//建立类
class Birth{
public:
Birth(int y,int m,int d);
~Birth();
void show();
private:
int year,month,day;
};
class Student{
public:
Student(string n,string i,int y,int m,int d);
~Student();
void show();
private:
string name;
string id;
//含有成员对象的类
Birth birth;
};
//定义构造函数
Birth::Birth(int y,int m,int d):year(y),month(m),day(d){
cout<<"Birth类的构造函数"<<endl;
}
Student::Student(string n,string i,int y,int m,int d):birth(y,m,d)//这里的birth为子对象
{
cout <<"Student类的构造函数"<<endl;
name=n;
id=i;
}
//列表初始化为:
// Student::Student(string n,string i,int y,int m,int d):name(n),id(i)birth(y,m,d){
// }
//析构函数
Birth::~Birth() {
cout << "Birth类的析构函数" << endl;
}
Student::~Student(){
cout<<"Student类的析构函数"<<endl;
}
//成员函数
void Birth::show(){
cout<<"出生日期为:"<<year<<"."<<month<<"."<<day<<endl;
}
void Student::show(){
cout << "姓名:" << name << endl;
cout << "学号:" << id << endl;
birth.show();//调用子对象的show函数
}
int main(){
Student student1("小明", "123456",2001,1,1);
student1.show();
return 0;
}
运行结果如下: