运算符重载练习完善日期
导语:利用运算符重载可以做很多的小项目,今天我们主要来做一点关于完善日期的方法,在原来的日期上加上一定的天数,或者自身加减,而引起的年的后移,还有两个日期之间相差的天数,都可通过运算符重载来实现。
#include"date.h"
class date
{
friend int getdaysmonth(int year, int month);
friend int leap(int year);
public:
date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
date operator+(int);//运算符重载+
date &operator++();//++
Int operator-(const date&d);//相减
private:
int _year;
int _month;
int _day;
//日期的合法性检测
if (year != 0 || month > 0 && month <= 12 || day > 0 && day <= 31)
{
_year = 1900;
_month = 1;
_day = 1;
}
};
date date:: operator+(int days)
{
date temp(*this);
temp._day += days;//先给日期将天数加上,变为了2018,5,105
int daysofmonth;
daysofmonth = getdaysmonth(temp._year, temp._month);//获得所在月的天数
if (temp._day > daysofmonth)//若超出了本来应该有的天数
{
temp._day -= daysofmonth;
temp._month++;//推到下一个月
//如果一直后推到了12月,则转向下一年
if (temp._month > 12)
{
temp._year++;
temp._month = 1;
}
}
//得出的结果为2018,8,13
return temp;
}
date& date:: operator++()
{
date temp(*this);
(*this)++;
return *this;
}
int getdaysmonth(int year, int month)
{
int daysofmonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2 && leap(year))//闰年的二月为29天
{
daysofmonth[1] += 1;
}
return daysofmonth[month - 1];
}
int leap(int year)
{
if (year % 4 && year % 10 || year % 40)
return 1;
}
int date::operator-(const date&d)
{
date temp(*this);
int daysofmonth;
int count = 0;//记录天数
count = count + temp._day;//先在记录天数上加上8月日期的天数
if (temp._month > d._month)
{
temp._month--;//移到前一个月
daysofmonth = getdaysmonth(temp._year, temp._month);//计算出前一个月的天数
count += daysofmonth;//更新记录天数
}
//前移到了5月,先计算5月的天数
daysofmonth = getdaysmonth(temp._year, temp._month);
count = count + daysofmonth - d._day;
return count;
}
int main()
{
date d(2018, 5, 5);
date d1(2018, 8, 10);
d = d + 100;
d1 - d;
d++;
++d;
}