C++面向对象程序设计课后作业第239页第5题
题目要求:设计一个日期类Date,包括年、月、日等私有数据成员。要求实现日期的基本运算,包括某日期加上指定天数、某日期减去指定天数、两个日期相差的天数等。
代码仅供参考
#include<iostream>
#include<math.h>
using namespace std;
class Date {
private:
int year; //年份
int month; //月份
int day; //天
long overDay; //总的天数
bool isLeap() { //判断闰年、平年
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0) return true;
else return false;
}
int* Months() { //计算本年每月天数
int months[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
if (this->isLeap()) months[1] += 1;
return months;
}
public:
Date(int day = 1, int month = 1, int year = 0001) {
this->year = year;
this->month = month;
this->day = day;
overDay = 0;
}
int OverDay() { //计算从0001年1月1日至今的天数
overDay = 0;
int* temp = this->Months();
for (int i = 0; i < this->month - 1; i++) { overDay += *temp++; }
overDay += day;
*temp = year - 1;
overDay += (*temp / 4 - *temp / 100 + *temp / 400) * 366 + (*temp - (*temp / 4 - *temp / 100 + *temp / 400)) * 365;
return overDay;
}
void Dispaly() { //打印时间
printf("%04d-%02d-%02d", year, month, day);
}
protected:
friend Date toDate(int); //声明友元函数——天数转化为格式化时间
friend Date operator- (Date date1, Date date2); //运算符重载“-”
friend Date operator+ (Date date1, Date date2); //运算符重载“+”
};
Date toDate(int days = 0) {
days = fabs(days);
Date date(31, 12, 1);
while (true)
{
if (date.OverDay() >= days) break;
date.year++;
}
int* day = (date.Months() + 11);
days = date.overDay - days;
for (int i = 0; i < 12; i++)
{
if (days >= *day)
{
days -= *day--;
date.month--;
}
else {
date.day = *day - days;
}
}
return date;
}
Date operator- (Date date1, Date date2) {
int days1 = date1.OverDay();
int days2 = date2.OverDay();
return toDate(days1 - days2);
}
Date operator+ (Date date1, Date date2) {
int days1 = date1.OverDay();
int days2 = date2.OverDay();
return toDate(days1 + days2);
}int main() {
Date date1(1, 3, 1970);
Date date2(27, 12, 2020);
Date date3 = date2 + 5;
cout << "date1:"; date1.Dispaly();
cout << "\ndate2:"; date2.Dispaly();
cout << "\ndate2 + 5="; date3.Dispaly();
date3 = date1 - 1;
cout << "\ndate1 - 1="; date3.Dispaly();
date3 = date1 - date2;
cout << "\ndate1 - date2="<<date3.OverDay() << "天";
return 0;
}