目录
头文件:
详细步骤:
第一步:计算闰年和判断日期是否合法
第二步:各类运算符重载
总代码:
我们今天实现一个简单的计算日期
我们这里先给出头文件,后面一个一个解释
头文件:
#pragma once
#include
using std::cout;
using std::endl;
using std::cin;
class Date
{
public:
//定义构造函数
Date(int year = 1900, int month = 1, int day = 1);
//打印日期
void Print()
{
cout << _year <<" " <<_month<<" " << _day << endl;
}
//运算符重载
Date operator+(int day);
Date operator-(int day);
Date& operator+=(int day);
Date& operator-=(int day);
bool operator<=(const Date& d);
bool operator>=(const Date& d);
bool operator>(const Date& d);
bool operator<(const Date& d);
bool operator==(const Date& d);
bool operator!=(const Date& d);
Date& operator++();//前置
Date operator++(int);//后置
Date& operator--();//前置
Date operator--(int);//后置
int operator-(Date d);//计算两个日期的差值
private:
int _year;
int _month;
int _day;
};
详细步骤:
第一步:计算闰年和判断日期是否合法
inline int GetMonthDay(int year, int month)
{
//多次调用的时候static能极大减小内存消耗,但是也可以删除,并不影响程序运行
static int _monthArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day = _monthArray[month];
if (month == 2 && (year % 4 == 0 && year % 100 != 0) || year % 400 == 0)//判断是否是闰年
{
day = 29;
}
return day;
}
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
if (!(year >= 0 && month >= 1 && month <= 12 && day > 0 && day <= GetMonthDay(year, month)))//看日期是否合法
{
cout << "fail" << endl;
exit(-1);
}
}
第一步:计算闰年和判断日期是否合法
inline int GetMonthDay(int year, int month)
{
//多次调用的时候static能极大减小内存消耗,但是也可以删除,并不影响程序运行
static int _monthArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day = _monthArray[month];
if (month == 2 && (year % 4 == 0 && year % 100 != 0) || year % 400 == 0)//判断是否是闰年
{
day = 29;
}
return day;
}
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
if (!(year >= 0 && month >= 1 && month <= 12 && day > 0 && day <= GetMonthDay(year, month)))//看日期是否合法
{
cout << "fail" << endl;
exit(-1);
}
}
我们将year,month,day赋值之后,首先进行判断,如果出现异常天数直接终结程序(如2022,1,32,这种不存在的日期)
随后一个问题就出来了,因为闰年和非闰年的2月不同,所以我们又使用一个函数getmonthday,来判断闰年的同时获取当月天数;
有些同学可能直接是【0,31,59(31+28 1月+2月),89(1月+2月+3月)......+.....365】
我们稍后再解释为什么要用我这种定义方式。
第二步:各类运算符重载
我们首先来看运算符”+”和”+=”
这是一般情况下的+
Date Date::operator+(int day)
{
Date tmp(*this);
tmp._day += day;
//判断天数是否大于当月的天数
while (tmp._day > GetMonthDay(tmp._year, tmp._month))
{
tmp._day -= GetMonthDay(tmp._year, tmp._month);
tmp._month++;
//判断月数是否大于12
if (tmp._month > 12)
{
tmp._year++;
tmp._month = 1;
}
}
return tmp;
}
这是一般情况下的+=
Date& Date::operator+=(int day)
{
Date ret(*this);
ret._day += day;
//判断天数是否超越了当月的天数
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
_month++;
//判断月数是否超过了12
if (_month > 12)
{
_year++;
_month = 1;
}
}
}
return *this;
}
我们可以发现两者其实都用了同一个while循环来判断日期是否合法。
我们可以选择将while循环打包成一个新的函数,也可以选择直接复用
+复用+=
Date Date::operator+(int day)
{
Date tmp(*this);
tmp += day;//直接调用operator的+=
return tmp;
}



