拯救小明(多继承+友元)

该博客介绍了一个编程题目,涉及日期和时间的比较。小明面临着作业截止时间的困扰,需要找出最早截止的作业。作者通过创建Date和Time类,以及Work类来表示作业,并实现了一个友元函数before进行时间比较。代码示例中,采用逐个读取并比较的方式找到最早截止的作业,最后输出结果。这是一个关于数据结构和算法的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

小明同学有着严重的拖延症,每次老师布置的作业都要到快要截止的时候才会开始动手完成,因此现在有着许许多多的作业完成。你是小明的好朋友,请帮小明找出最紧急的作业(即最早截止的作业)。

要求如下:

1.定义一个日期类Date,包括三个protected成员数据year,month,day;

2.定义一个时间类Time,包括三个protected成员数据hour,minute,second(12小时制);

3.以Date类和Time类为基类,创建一个作业类Work,包括新增成员:int ID;作业的ID

4.定义一个友元函数bool before(const Work& w1,const Work& w2);//判断作业w1的时间是否早于作业w2的时间。

输入

输入若干作业,每个作业占一行(作业ID 年 月 日 时 分 秒)

当输入0时结束,相应的结果不要输出。

输出

时间最靠前的作业。

输入样例1 

1 2021 9 25 4 5 6
2 2020 6 13 5 7 8
3 2021 8 21 6 7 9
5 2022 7 8 9 10 11
4 2021 7 26 5 25 30
0

输出样例1

The urgent Work is No.2: 2020/06/13 05:07:08

思路分析

根据输出我们可以知道,没有办法用数组排序的方法去做,因为不知道有多少个。

所以只能读取一个比较一个,我们把第一个读取的作为最早的作业的,然后后面每读取一个都与之做判断,用友元函数before去比较,发现更早的就把新的赋值给旧的,最后输出。

我们把友元函数before写成像sort函数排序规则那样,从年份开始判断,相等的再判断月份,依次到日、小时、分组、秒。

AC代码

#include<iostream>
#include"iomanip" 
#include<string>
using namespace std;
class Date
{
	protected:
		int year,month,day;
	public:
		Date(int year,int month,int day):year(year),month(month),day(day){}
};
class Time
{
	protected:
		int hour,minute,second;
	public:
		Time(int hour,int minute,int second):hour(hour),minute(minute),second(second){}
};
class Work:public Date,public Time
{
	protected:
		int ID;
	public:
		Work(int ID,int year,int month,int day,int hour,int minute,int second):ID(ID),Date(year,month,day),Time(hour,minute,second){}
		void print(){cout<<"The urgent Work is No."<<ID<<": "<<year<<"/"<<setw(2)<<setfill('0')<<month<<"/"<<setw(2)<<setfill('0')<<day<<' '<<setw(2)<<setfill('0')<<hour<<':'<<setw(2)<<setfill('0')<<minute<<':'<<setw(2)<<setfill('0')<<second<<endl;}
		friend bool before(const Work&w1,const Work&w2);
};
bool before(const Work & w1,const Work & w2)
{
	if(w1.year<w2.year)
	return 1;
	else if(w1.year>w2.year)
	return 0;
	if(w1.month<w2.month)
	return 1;
	else if(w1.month>w2.month)
	return 0;
	if(w1.day<w2.day)
	return 1;
	else if(w1.day>w2.day)
	return 0;
	if(w1.hour<w2.hour)
	return 1;
	else if(w1.hour>w2.hour)
	return 0;
	if(w1.minute<w2.minute)
	return 1;
	else if(w1.minute>w2.minute)
	return 0;
	if(w1.second<w2.second)
	return 1;
	else if(w1.second>w2.second)
	return 0;	
}
int main()
{
	int ID,year,month,day,hour,minute,second;
	cin>>ID>>year>>month>>day>>hour>>minute>>second;
	Work w1(ID,year,month,day,hour,minute,second);
	while(1)
	{
		cin>>ID;
		if(ID==0)
		break;
		cin>>year>>month>>day>>hour>>minute>>second;
		Work w2(ID,year,month,day,hour,minute,second);
		if(before(w1,w2)==0)
		w1=w2;	
	}
	w1.print();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员萌芽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值