派生类的构造函数和析构函数

在继承与派生的关系中,派生类会继承基类全部函数,但是不包括构造和析构函数。

解决这个问题的思路是在派生类的构造函数中调用基类构造函数,由基类的构造函数负责完全对基类成员变量的初始化工作。

(1)构造函数调用顺序

       1.先调用基类构造函数

       2.再调用子对象构造函数

       3.最后调用派生类构造函数

(2)析构函数调用顺序:

       1.先调用派生类构造函数

       2.再调用子对象构造函数

       3.最后调用基类构造函数

#include<iostream>
#include<string>
using namespace std;
class Time
{
	public:
		Time(int y,int mo,int d)
		{
			year=y;
			month=mo;
			day=d;
			cout<<"子对象time构造函数被调用!"<<endl;
		}
		~Time()
		{
			cout<<"子对象time析构函数被调用!"<<endl;
		}
		void ShowTime()
		{
			cout<<"year:"<<year<<endl;
			cout<<"month:"<<month<<endl;
			cout<<"day:"<<day<<endl;
		 } 
	private:
		int year;
		int month;
		int day;
};
class Clock
{
	public:
		Clock(int h,int m,int s);
		void ShowClock()
		{
			cout<<"hour:"<<hour<<endl;
			cout<<"minute:"<<minute<<endl;
			cout<<"second:"<<second<<endl;
		}
		~Clock()
		{
			cout<<"基类Clock析构函数被调用!"<<endl;
		}
	protected:
		int hour;
		int minute;
		int second;
};
class Date:public Clock
{
	public:
		Date(int h,int m,int s,string w,int y,int mo,int d):time(y,mo,d), Clock(h,m,s)
		{
			week=w;
			cout<<"派生类Date构造函数被调用!"<<endl;
		 } 
		 ~Date()
		 {
		 	cout<<"派生类Date析构函数被调用!"<<endl;
		 }
		 void ShowDate()
		 {
		 	time.ShowTime();
		 	cout<<"week:"<<week<<endl;
		 	ShowClock();
		 }
	private:
		string week;
		Time time;
};
Clock::Clock(int h,int m,int s)
{
	hour=h;
	minute=m;
	second=s;
	cout<<"基类Clock构造函数被调用!"<<endl;
}
int main()
{
	Date d(15,5,30,"星期六",2022,5,14);
	d.ShowDate();
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值