在Date类中
成员变量
private:
int _year;
int _month;
int _day;
日期类的构造函数(年月日)
public:
Date(int year,int month,int day){
_year = year;
_month = month;
_day = day;
}
输出函数(输出年月日)
void display(){
cout<<_year<<"."<<_month<<"."<<_day<<endl;
}
判断是否为闰年
bool IsLeapYear(int year){
if(year%4==0 && year%100!=0 || year%400==0){
return true;
}
return false;
}
得到固定月的天数
int GetMonthDay(int year,int month){
int days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if(IsLeapYear(year) && month == 2){
return 29;
}else{
return days[month];
}
}
运算符重载(==,!=,<)
bool operator==(co 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;
}else if(_month < d._month){
return true;
}else(_day < d._day){
return true;
}
return false;
}
运算符重载(+=,+,-=,-)
Date& operator+=(int day){
_day += day;
while(_day > GetMonthDay(_year,_month)){
_day -= GetMonthDay(_year,_month);
++_month;
}
if(_month > 12){
++_year;
}
return *this;
}
Date operator+(int day){
Date ret(*this);
ret += day;
return ret;
}
Date& operator-=(int day){
_day -= day;
while(_day <= 0){
--_month;
if(_month == 0){
--_year;
_month = 12;
}
_day += GetMonthDay(_year,_month);
}
return *this;
}
Date operator-(int day){
Date ret(*this);
ret-=day;
return ret;
}
前置++,后置++
Date& operator++(){
*this += 1;
return *this;
}
Date operator++(int){
Date ret(*this);
*this += 1;
return ret;
}