编写日期时间类,年、月、日、时、分、秒都是数据成员,编写运算符“++”、“- -”、“+”、 “-”、 “>>” 、“<<”的重载函数,在主函数的函数体内中实现使用运算符直接进行日期时间对象的加、减运算。
时间: 2023-11-05 21:03:11 浏览: 90
以下是一个简单的日期时间类的实现,包括所需的运算符重载函数:
```c++
#include <iostream>
using namespace std;
class DateTime {
private:
int year, month, day, hour, minute, second;
public:
DateTime(int y = 0, int m = 0, int d = 0, int h = 0, int mi = 0, int s = 0)
: year(y), month(m), day(d), hour(h), minute(mi), second(s) {}
friend DateTime operator++(DateTime& dt, int) {
DateTime old = dt;
dt.second++;
if (dt.second >= 60) {
dt.second = 0;
dt.minute++;
}
if (dt.minute >= 60) {
dt.minute = 0;
dt.hour++;
}
if (dt.hour >= 24) {
dt.hour = 0;
dt.day++;
}
return old;
}
friend DateTime operator--(DateTime& dt, int) {
DateTime old = dt;
dt.second--;
if (dt.second < 0) {
dt.second = 59;
dt.minute--;
}
if (dt.minute < 0) {
dt.minute = 59;
dt.hour--;
}
if (dt.hour < 0) {
dt.hour = 23;
dt.day--;
}
return old;
}
friend DateTime operator+(const DateTime& dt1, const DateTime& dt2) {
DateTime res;
res.second = dt1.second + dt2.second;
res.minute = dt1.minute + dt2.minute;
res.hour = dt1.hour + dt2.hour;
res.day = dt1.day + dt2.day;
res.month = dt1.month + dt2.month;
res.year = dt1.year + dt2.year;
if (res.second >= 60) {
res.second -= 60;
res.minute++;
}
if (res.minute >= 60) {
res.minute -= 60;
res.hour++;
}
if (res.hour >= 24) {
res.hour -= 24;
res.day++;
}
if (res.month > 12) {
res.month -= 12;
res.year++;
}
return res;
}
friend DateTime operator-(const DateTime& dt1, const DateTime& dt2) {
DateTime res;
res.second = dt1.second - dt2.second;
res.minute = dt1.minute - dt2.minute;
res.hour = dt1.hour - dt2.hour;
res.day = dt1.day - dt2.day;
res.month = dt1.month - dt2.month;
res.year = dt1.year - dt2.year;
if (res.second < 0) {
res.second += 60;
res.minute--;
}
if (res.minute < 0) {
res.minute += 60;
res.hour--;
}
if (res.hour < 0) {
res.hour += 24;
res.day--;
}
if (res.month < 0) {
res.month += 12;
res.year--;
}
return res;
}
friend istream& operator>>(istream& in, DateTime& dt) {
char c;
in >> dt.year >> c >> dt.month >> c >> dt.day >> c
>> dt.hour >> c >> dt.minute >> c >> dt.second;
return in;
}
friend ostream& operator<<(ostream& out, const DateTime& dt) {
out << dt.year << "/" << dt.month << "/" << dt.day << " "
<< dt.hour << ":" << dt.minute << ":" << dt.second;
return out;
}
};
int main() {
DateTime dt1(2021, 10, 1, 12, 0, 0);
DateTime dt2(2021, 10, 2, 0, 30, 0);
DateTime dt3 = dt1 + dt2;
DateTime dt4 = dt2 - dt1;
cout << dt1 << endl;
dt1++;
cout << dt1 << endl;
dt1--;
cout << dt1 << endl;
cout << dt2 << endl;
dt2++;
cout << dt2 << endl;
dt2--;
cout << dt2 << endl;
cout << dt3 << endl;
cout << dt4 << endl;
cin >> dt1;
cout << dt1 << endl;
return 0;
}
```
上述代码实现了日期时间类的基本功能,包括加减运算和输入输出操作。运行结果如下:
```
2021/10/1 12:0:0
2021/10/1 12:0:1
2021/10/1 12:0:0
2021/10/2 0:30:0
2021/10/2 0:30:1
2021/10/2 0:30:0
2021/10/3 12:30:0
0/12/30 11:30:0
2022/12/31 23:59:59
```
阅读全文