#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Date
{
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
//构造
Date (int year = 1900, int month = 1, int day = 1)
:_year(year)
,_month(month)
,_day(day)
{
;
}
//拷贝构造
Date (const Date& d)
:_year(d._year)
,_month(d._month)
,_day(d._day)
{
;
}
void Display()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
//判断该月天数
//静态成员函数只能调静态函数,不能访问私有成员,因为没this
static int GetMonthDays(int year, int month)
{
//年月不合法返回-1,注:不能用IsInvalid判断,否则就会递归GetMonthDays
if (year <1900 || month < 1 || month > 12)
{
return -1;
}
static int arr[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = arr[month];
if (month == 2 && IsLeapYear(year)) //月份判断开销小,放前面
{
days++;
}
return days;
}
//判断闰年
static bool IsLeapYear(int year)
{
return ((year%4 == 0)&&(year%100 != 0)) || (year%400 == 0);
}
//判断日期是否合法
bool IsInvalid()
{
return (_year >= 1900
&& _month > 0 && _month < 13
&& _day > 0 && _day <= GetMonthDays(_year, _month));
}
bool operator>(const Date& d) const
{
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) const
{
return (_year == d._year)
&& (_month == d._month)
&& (_day == d._day);
}
Date operator+(int day) const
{
if (day < 0)
{
return *this - (-day);
}
Date tmp(*this);
tmp._day += day;
while(!tmp.IsInvalid())
{
tmp._day -= GetMonthDays(tmp._year, tmp._month);
tmp._month++;
if (tmp._month == 13)
{
tmp._year++;
tmp._month = 1;
}
}
return tmp;
}
Date operator-(int day) const
{
if (day < 0)
{
return *this + (-day);
}
Date tmp(*this);
tmp._day -= day;
while(!tmp.IsInvalid())
{
tmp._month--;
if (tmp._month == 0)
{
tmp._year--;
tmp._month = 12;
}
tmp._day += GetMonthDays(tmp._year, tmp._month);
}
return tmp;
}
bool operator!=(const Date& d) const
{
return !(*this == d);
}
Date& operator=(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}
bool operator<(const Date& d) const
{
return !(*this > d || *this == d);
}
Date& operator+=(int day)
{
*this = *this + day;
return *this;
}
Date& operator++() //前置++,后返回
{
*this += 1;
return *this;
}
Date operator++(int) //后置++,先返回
{
Date tmp(*this);
tmp += 1;
return tmp;
}
//日期-日期
int operator-(const Date& d) const
{
Date min(*this);
Date max(d);
int tag = -1;
int count = 0;
if (d < *this)
{
min = d;
max = *this;
tag = 1;
}
while(min != max)
{
//后置++调了4次构造
//前置++调了2次构造,高效
++min;
count++;
}
return count*tag;
}
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& out, const Date& d)
{
out<<d._year<<"-"<<d._month<<"-"<<d._day<<endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
cout<<"输入年月日"<<endl;
in>>d._year;
in>>d._month;
in>>d._day;
return in;
}
int main()
{
Date a;
cin>>a;
cout<<a<<endl;
return 0;
}
日期类 class_Date
最新推荐文章于 2023-01-09 21:50:35 发布