#include<iostream>
#include<assert.h>
using namespace std;
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
:_year(year),_month(month),_day(day)
{
assert(year >= 1900);
assert(month > 0 && month < 13);
assert(day > 0 && day <= GetMonDay(year, month));
}
//赋值运算符重载
Date& operator=(const Date& d)
{
if(*this != d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
//计算一个日期加减一个天数的运算符重载
Date operator+(int day)
{
Date tmp(*this);
if(day<0)
{
day = -day;
return (tmp - day);
}
if(day == 0)
{
return tmp;
}
else
tmp._day += day;
if(tmp._day > GetMonDay(tmp._year,tmp._month))
{
tmp._day -= GetMonDay(tmp._year,tmp._month);
if(tmp._month == 12)
{
tmp._year++;
tmp._month = 1;
}
else
{
tmp._month++;
}
}
return tmp;
}
Date operator+=(int day)
{
Date tmp(*this);
tmp = *this + day;
*this = tmp;
return *this;
}
Date operator-(int day)
{
Date tmp(*this);
if(day<0)
{
day = -day;
return(tmp + day);
}
if(day == 0)
{
return tmp;
}
else
tmp._day -= day;
while(tmp._day<=0)
{
if(tmp._month == 1)
{
tmp._year--;
tmp._month = 12;
}
else
{
tmp._month--;
}
tmp._day = GetMonDay(tmp._year,tmp._month)+tmp._day;
}
return tmp;
}
Date operator-=(int day)
{
Date tmp(*this);
tmp = *this - day;
*this = tmp;
return *this;
}
Date operator++()
{
*this += 1;
return *this;
}
Date operator++(int)//后置++
{
Date tmp(*this);
*this += 1;
return tmp;
}
Date operator--()
{
*this -= 1;
return *this;
}
Date operator--(int)//后置--
{
Date tmp(*this);
*this -= 1;
return tmp;
}
//比较运算符的重载
bool operator==(const Date& d)
{
return (_year == d._year && _month == d._month && _day == d._day);
}
bool operator!=(const Date &d)
{
return !(*this == d);
}
bool operator >(const Date& d)
{
if(_year > d._year)
{
return true;
}
if(_year == d._year)
{
if(_month > d._month)
{
return true;
}
if(_month == d._month)
{
if(_day > d._day)
{
return true;
}
}
}
return false;
}
bool operator>=(const Date& d)
{
return (*this > d || *this == d);
}
bool operator <(const Date& d)
{
return !(*this >= d);
}
bool operator<=(const Date& d)
{
return !(*this>d);
}
int GetMonDay(int year, int month)
{
assert(year >= 1900);
assert(month > 0 && month < 13);
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%400 || (year%4 && year%100)))
{
day+=1;
}
return day;
}
//计算两个日期相减
int operator-(const Date& d)
{
int count = 0;
Date d1 = *this;
Date d2 = d;
if(*this > d)
{
d1 = d;
d2 = *this;
}
while(d1!=d2)
{
d1+=1;
count++;
}
return count;
}
void Display()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
private:
int _year;
int _month;
int _day;
};
void Test()
{
Date d1(2015,12,1);
Date d2(2015,12,23);
int count;
count = d2-d1;
cout<<count<<endl;
d2 = d1;
d2.Display();
//cout<<(d1==d2)<<endl;
//cout<<(d1!=d2)<<endl;
//cout<<(d1>d2)<<endl;
//cout<<(d1>=d2)<<endl;
//cout<<(d1<d2)<<endl;
//cout<<(d1<=d2)<<endl;
// d.Display();
}
int main()
{
Test();
return 0;
}
【c++】用c++实现Date类
最新推荐文章于 2024-10-07 16:38:05 发布