#pragma once
#include < iostream>
using std::cout;
using std::cin;
using std::endl;classDate{public:// 获取某年某月的天数
int GetMonthDay(int year, int month);// 全缺省的构造函数Date(int year =0, int month =1, int day =1);voidPrint();//析构,拷贝构造,赋值重载函数可以不用写,默认生成的就够用//日期+=天数
Date& operator+=(int day);// 日+天数
Date operator+(int day);// 日期-天数
Date operator-(int day);// 日期-=天数
Date& operator-=(int day);// 前置++
Date& operator++();// 后置++
Date operator++(int);//后置--
Date operator--(int);// 前置--
Date& operator--();// >运算符重载
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);// 日期-日期 返回天数
int operator-(const Date& d);private:
int _year;
int _month;
int _day;};
确定某年某月有多少天
//因为闰年和平年二月份的天数不一样,随便加加减减会有问题,这个函数可以根据闰年和平年给出对应的天数//因为后面需要频繁调用它,设置成内联函数
inline int Date::GetMonthDay(int year, int month){//设置成静态变量,不用每次调用这个函数都开辟一个数组static int arr[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int day = arr[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){//防止给的日期有错误if(year >=0&& month >0&& month <13&& day >0&& day <=GetMonthDay(year, month)){
_year = year;
_month = month;
_day = day;}else{
cout <<"非法日期"<< endl;
cout << year <<"年"<< month <<"月"<< day <<"日"<< endl;}}
//返回的是++前的值,不能传引用返回//为了和前置++赋值重载函数构成函数重载,需要加个int ,不需要传实参,因为没用,如果不加参数那么前置++和后置++函数就一样了,们在进行前置++或者后置++操作时,编译器就不知道调用哪一个了
Date Date::operator++(int){
Date ret(*this);*this+=1;return ret;}
后置–
//返回原对象,然后对象再--
Date Date::operator--(int){
Date ret =*this;*this-=1;return ret;}
int Date::operator-(const Date& d){
Date min =*this;
Date max = d;int flag =-1;int daycount =0;if(*this> d){
min = d;
max =*this;
flag =1;}while(min != max){++min;
daycount++;}return flag * daycount;}