#include<iostream>
using namespace std;
class Data
{
public:
//带参的缺省的构造函数
Data(int year=1900,int month=1,int day=1)
{
if(year<1900||
month<1||month>12
||day<1||day>GetMonthDay(year,month))
{
cout<<"非法日期"<<endl;
}
_year=year;
_month=month;
_day=day;
}
Data(const Data& d)//使用同类型对象
{
this->_year=d._year;
this->_month=d._month;
this->_day=d._day;
}
Data& operator=(const Data& d)
{
if(this!=&d)
{
_year=d._year;
_month=d._month;
_day=d._day;
}
return *this;
}
void Display()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
//判断日期是否相等
bool operator==(const Data& d)
{
return _year==d._year
&&_month==d._month
&&_day==d._day;
}
//日期-日期 找一个参照日期。
Data operator-(const Data& d)
{
int flag=1;
Data max=*this;//拷贝构造
Data min=d;//拷贝构造
if(*this<d)
{
max=d;//调用赋值函数
min=*this;
flag=-1;
}
int day=0;//天数计数器
while(min<max)
{
++(min);
++day;
}
return day*flag;
}
Data operator+=(int day)
{
//d1+10 d1的值不需要改变,所以拷贝构造一个临时变量
if(_day<0)
{
return *this-=-day;
}
_day+=day;
while(_day>GetMonDay(_year,_day))
{
_day-=GetMonDay(_year,_day);
_month++;
if(_month==13)
{
_year++;
_month=1;
}
}
return *this;
}
// d1+=10 调用operate+=提高代码复用性
Data operator+(int day)
{
Data ret(*this);
ret+=day;
return ret;
}
Data operator-(int day)
{
Data ret(*this);
ret-=day;
return ret;
}
Data operator-=(int day)
{
if(day<0)
{
return *this+=-day;
}
_day-=day;
while(_day<=0)
{
--_month;
if(_month==0)
{
--_year;
_month=12;
}
_day+=GetMonDay(_year,_month);
}
return *this;
}
//d1++ ->d.operator++(&d)
Data operator++()//前置++
{
*this+=1;
return *this;
}
//++d1 ->d.operator++(&d,0)
Data operator++(int)//后置++
{
Data ret(*this);
*this+=1;
return ret;
}
Data operator--()
{
*this-=1;
return *this;
}
Data operator--(int)
{
Data tmp(*this);
(*this)-=1;
return *this;
}
//d1>d2
bool operator>(const Data& 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 Data& d)
{
return *this >d ||*this==d;
}
bool operator<(const Data& d)
{
return !(*this>=d);
}
bool operator<=(const Data& d)
{
return !(*this>d);
}
//判断日期是否相等
bool operator!=(const Data& d)
{
return !(*this==d);
}
//获得每月的天数
int GetMonDay(int year,int month)
{
static int days[13]={
0,31,28,31,30,31,30,31,31,30,31,30,31
}
int day=days[month];
if(month==2&&
&&year%4==0&&year%100!=0
||year%400==0)
{
day+=1;
}
return day;
}
private:
int _year;
int _month;
int _day;
};
C++学习-Data日期类实现
猜你喜欢
转载自blog.csdn.net/zgege/article/details/81270850
今日推荐
周排行