D. 日程安排(多继承+友元函数)
题目描述
已有一个日期类Date,包括三个protected成员数据year,month,day;
另有一个时间类Time,包括三个protected成员数据hour,minute,second,12小时制;
现需根据输入的日程的日期时间,安排前后顺序,为此以Date类和Time类为基类,建立一个日程类Schedule,包括以下新增成员:
int ID;//日程的ID
定义友元函数bool before(const Schedule & s1,const Schedule & s2);//判断日程s1时间是否早于日程s2。
编写主函数,根据输入的各项日程信息,建立日程对象,找出需要最早安排的日程(日期和时间相等时,输出较早建立的日程),并输出该日程对象的信息。
输入
测试输入包含若干日程,每个日程占一行(日程ID日程日期日程时间)。
当读入0时输入结束,相应的结果不要输出。
输出
时间最靠前的日程
输入样例
1 2019 6 27 8 0 1
2 2019 6 28 8 0 1
3 2020 1 1 8 0 0
0
输出样例
The urgent schedule is No.1: 2019/06/27 08:00:01
参考代码
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
class Date //日期类Date
{
protected: //包括三个protected成员数据year,month,day;
int year, month, day;
public:
Date(int a = 0, int b = 0, int c = 0) : year(a), month(b), day(c){}; //构造函数,初始化参数列表
};
class Time //时间类Time
{
protected:
int hour, minute, second; //包括三个protected成员数据hour,minute,second
public:
Time(int a = 0, int b = 0, int c = 0) : hour(a), minute(b), second(c){}; //构造函数,初始化参数列表
};
//需根据输入的日程的日期时间,安排前后顺序
class Schedule : public Date, public Time //以Date类和Time类为基类,建立一个日程类Schedule
{
protected:
int ID; //新增成员,日程的ID
public:
Schedule(const Date &p, const Time &q, int ID = 0) : Date(p), Time(q), ID(ID) {} //构造函数,初始化参数列表
friend bool before(const Schedule &S1, const Schedule &S2); //友元函数
void display() //函数输出
{
cout << "The urgent schedule is No." << ID << ": " << year << "/" << setw(2) << setfill('0') << month << "/" << setw(2) << setfill('0') << day << " ";
cout << setw(2) << setfill('0') << hour << ":" << setw(2) << setfill('0') << minute << ":" << setw(2) << setfill('0') << second << endl;
}
};
bool before(const Schedule &S1, const Schedule &S2) //判断日程s1时间是否早于日程s2。
{
int sum1, sum2;
sum1 = S1.year * 10000 + S1.month * 100 + S1.day + S1.hour * 3600 + S1.minute * 60 + S1.second;
sum2 = S2.year * 10000 + S2.month * 100 + S2.day + S2.hour * 3600 + S2.minute * 60 + S2.second;
return sum1 < sum2; //日期和时间相等时,输出较早建立的日程
}
int main()
{
int id;
Date D(10000, 0, 0);
Time T(0, 0, 0);
Schedule S_MAX(D, T, 10000); //先把时间设置的够大
while (cin >> id)
{
if (id == 0)
break;
else
{
int y, m, d, h, min, s;
cin >> y >> m >> d >> h >> min >> s;
Date D1(y, m, d);
Time T1(h, min, s);
Schedule S1(D1, T1, id);
if (before(S1, S_MAX))
S_MAX = S1; //找出最小的时间
}
}
S_MAX.display();
return 0;
}