7.5 应用实例—日期和时间
下面是一个有关日期(年、月、日)和时间(时、分、秒)的程序。该程序建立了三个类,分别是日期类Date
、时间类Time
和基于前两个类派生的日期和时间类TimeDate
。
程序代码
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef char string80[80];
class Date {
public:
Date() {}
Date(int y, int m, int d) {
SetDate(y, m, d);
}
void SetDate(int y, int m, int d) {
Year = y;
Month = m;
Day = d;
}
void GetStringDate(string80 &Date) {
sprintf(Date, "%d/%d/%d", Year, Month, Day);
}
protected:
int Year, Month, Day;
};
class Time {
public:
Time() {}
Time(int h, int m, int s) {
SetTime(h, m, s);
}
void SetTime(int h, int m, int s) {
Hours = h;
Minutes = m;
Seconds = s;
}
void GetStringTime(string80 &Time) {
sprintf(Time, "%d:%d:%d", Hours, Minutes, Seconds);
}
protected:
int Hours, Minutes, Seconds;
};
class TimeDate : public Date, public Time {
public:
TimeDate() : Date(), Time() {}
TimeDate(int y, int mo, int d, int h, int mi, int s) : Date(y, mo, d), Time(h, mi, s) {}
void GetStringDT(string80 &DTstr) {
sprintf(DTstr, "%d/%d/%d %d:%d:%d", Year, Month, Day, Hours, Minutes, Seconds);
}
};
int main() {
TimeDate datel, date2(1998, 8, 12, 12, 45, 10);
string80 DemoStr;
datel.SetDate(1998, 8, 7);
datel.SetTime(10, 30, 45);
datel.GetStringDT(DemoStr);
cout << "The datel date and time is " << DemoStr << endl;
datel.GetStringDate(DemoStr);
cout << "The datel date is " << DemoStr << endl;
datel.GetStringTime(DemoStr);
cout << "The datel time is " << DemoStr << endl;
date2.GetStringDT(DemoStr);
cout << "The date2 date and time is " << DemoStr << endl;
return 0;
}
程序说明
输出结果:
The datel date and time is 1998/8/7 10:30:45
The datel date is 1998/8/7
The datel time is 10:30:45
The date2 date and time is 1998/8/12 12:45:10
说明:
-
程序包含的头文件:
#include <iostream>
:标准输入输出流库。#include <string.h>
:字符串操作函数库。#include <stdio.h>
:标准输入输出函数库,包括sprintf
函数。
-
类型定义:
typedef char string80[80];
该语句定义了一个新的类型
string80
,它是char
型的一维数组,有80个元素。 -
类关系: 程序中定义了三个类:
Date
、Time
和TimeDate
。TimeDate
类通过多继承继承了Date
类和Time
类。Date
类:用于表示日期,包含年、月、日三个成员。Time
类:用于表示时间,包含时、分、秒三个成员。TimeDate
类:继承自Date
和Time
,用于同时表示日期和时间。
关系图如下:
Date Time TimeDate
-
构造函数:
Date
类和Time
类分别有默认构造函数和带参数的构造函数,用于初始化日期和时间。TimeDate
类的构造函数调用了其两个基类的构造函数来初始化日期和时间。
-
成员函数:
GetStringDate
:将日期转换为字符串格式。GetStringTime
:将时间转换为字符串格式。GetStringDT
:将日期和时间转换为字符串格式。
小结
本实例通过多继承实现了日期和时间的组合,展示了继承和成员函数的使用方法。通过使用typedef
定义新类型和sprintf
格式化字符串,使得代码更加简洁和易读。通过这种方式,可以方便地操作日期和时间数据,进行格式化输出。