C++类与对象(内含成员对象)③

#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;
}

运行结果如下:
在这里插入图片描述

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值