实现功能:
①两个日期的大小比较
②日期加减天数后的日期
③日期的自增自减
④日期减日期所得天数
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 1900,int month = 1,int day = 1) //列表初始化
:_year(year)
,_month(month)
,_day(day)
{}//构造函数 初始化
void Print()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
int GetMonthDay()//获取月份天数
{
static int monthdays[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if(this-> _month == 2 &&
((this-> _year%4 == 0 && this-> _year%100 != 0)
|| this-> _year%400 == 0))
return 29;
return monthdays[this-> _month];
}
bool IsTnvalid()//防御
{
if(_year >= 0 &&
_month > 0 && _month < 13 &&
_day > 0 && _day <= GetMonthDay())
return true;
return false;
}
bool operator>(const Date& d)
{
if(_year > d._year)
return true;
else if(_year == d._year)
{
if(_month > d._month)
return true;
else if(_month == d._month)
{
if(_day >d._day)
return true;
}
}
return false;
}
bool operator==(const Date& d)
{
if (_year == d._year &&
_month == d._month &&
_day == d._day )
return true;
else
return false;
}
bool operator<(const Date& d)
{
return !(*this >d || *this == d);
}
Date operator+(int day)//日期+天数
{
Date tmp(*this); //拷贝构造
tmp._day += day;
while(tmp._day > tmp.GetMonthDay())
{
tmp._day -= tmp.GetMonthDay();
tmp._month ++;
if(tmp._month > 12)
{
tmp._year++;
tmp._month = 1;
}
}
return tmp;
}
Date operator-(int day)//日期- 天数
{
Date tmp = *this;
tmp._day -= day;
while(tmp._day <1)
{
tmp._month--;
tmp._day += tmp.GetMonthDay();
if(tmp._month <1)
{
tmp._year--;
tmp._month = 12;
}
}
return tmp;
}
Date& operator++() //前置
{
*this = *this + 1;
return *this;
}
Date& operator++(int)//后置
{
Date tmp(*this);
*this = *this + 1;
return tmp;
}
Date& operator--()// 前置--
{
*this = *this - 1;
return *this;
}
Date& operator--(int)//后置--
{
Date tmp = *this;
*this = *this - 1;
return tmp;
}
int operator-(const Date& d) //日期-日期
{
int tag = 1;
int count = 0;
Date great(*this);
Date less(d);
if(*this <d)
{
great = d;
less = *this;
tag = -1;
}
while(less < great)
{
++count;
++less;
}
return count *tag;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2(1997,9,12);
Date d3(d1);
//d1.Print();
//d2.Print();
//d3.Print();
//cout<<(d1.operator>(d2))<<endl;
//cout<<(d1.operator==(d3))<<endl;
//cout<<(d1.operator<(d2))<<endl;
Date d4 = d2 + 77;
Date d5 = d4 - 77;
cout<<(d4.operator-(d5))<<endl;
d4.Print();
d5.Print();
system("pause");
}