【类和对象】 继承和派生——定义Date类和Time类并派生出DateTime类

题目:
在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;

string itoa(int n, string &s)            //这里用string代替了char类型 
{
	string a;
	int n1=n,t;
	while(n1)
	{
		t=n1%10;
		n1/=10;
		switch(t)
		{
			case 0: a+="0";break;
			case 1: a+="1";break;
			case 2: a+="2";break;
			case 3: a+="3";break;
			case 4: a+="4";break;
			case 5: a+="5";break;
			case 6: a+="6";break;
			case 7: a+="7";break;
			case 8:	a+="8";break;
			case 9: a+="9";break;
		}
	}
	
	string b;
	for(int i=a.size()-1;i>=0;i--)
		b+=a[i];
	s=b;
	return s;	
} 

//定义日期类 
class Date
{
	protected:
		int year;
		int month;
		int day;
	public:
		Date(int y=0000, int mon=00, int d=00)        //初始化构造函数 
		{
			year=y;
			month=mon;
			day=d;
		}
		void SetDate(int y, int mon, int d)
		{
			year=y;
			month=mon;
			day=d;
		}
		void GetDate(string &a)
		{
			string s;
			itoa(year,s);
			a=s+"/";
			itoa(month,s);
			a=a+s+"/";
			itoa(day,s);
			a=a+s;
		}
};

//定义时间类 
class Time
{
	protected:
		int hour;
		int minute;
		int second;
	public:
		Time(int h=00, int m=00, int s=00)           //初始化构造函数
		{
			hour=h;
			minute=m;
			second=s;
		}
		void SetTime(int h, int m, int s)
		{
			hour=h;
			minute=m;
			second=s;
		}
		void GetTime(string &a)
		{
			string s;
			itoa(hour,s);
			a=s+":";
			itoa(minute,s);
			a=a+s+":";
			itoa(second,s);
			a=a+s;
		}
};

//定义日期和时间类 
class DateTime:public Date,public Time
{
	public:
		DateTime(int y, int mon, int d, int h, int m, int s):Date(y,mon,d),Time(h,m,s){}
		void SetDateTime(int y,int mon,int d,int h,int m,int s)
		{
			SetDate(y,mon,d);
			SetTime(h,m,s);		
		}
		void GetDateTime(string &a)
		{
			string s;
			GetDate(s);			
			a=s+'\n';
			GetTime(s);
			a=a+s;
		}
};

int main()
{
	int year,month,day,hour,minute,second;
	cout<<"请输入日期和时间:"<<endl; 
	cin>>year>>month>>day>>hour>>minute>>second;
	DateTime d1(year,month,day,hour,minute,second);
	Date d2(year,month,day);
	cout<<endl;
	string a;
	d1.GetDateTime(a);
	cout<<a;
	
	return 0;
}
  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值