/*
设计日期类(Date),重载下列运算符实现相关操作:
(1)重载-(日期相差天数)
(2)重载+(Date+int)
(3)重载+(int+Date)
(4)重载++ ( Date d; d++; ++d; ++++d)
*/
# include <iostream.h>
//using namespace std;
class Date
{
public:
Date(int y,int m,int d);
int operator - (Date & date2);
friend Date operator + (Date &date1,int num);
friend Date operator + (int num,Date &date1);
Date& operator ++ ();
Date operator ++(int);
int daycount();
void adjust();
void show();
private:
int year,month,day;
};
bool isLeapYear(int i)
{
return ( i%4 == 0 && i%100 != 0 )||( i%400 == 0);
}
void Date::adjust()
{
int Month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(isLeapYear(year))
Month[2]++;
if(day>Month[month])
{
day-=Month[month];
month++;
}
if(month==13)
{
month=1;
year++;
}
}
Date operator + (Date &date1,int num)
{
Date temp(date1);
temp.day=date1.day+num;
temp.adjust();
return temp;
}
Date operator + (int num,Date &date1)
{
Date temp(date1);
temp.day=date1.day+num;
temp.adjust();
return temp;
}
int Date :: daycount()
{
int dayOfMonth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31},i,sum=0;
for(i=1;i<month;i++)
sum+=dayOfMonth[i];
sum+=day;
if(isLeapYear(year))
sum+=1;
for(i=1;i<year;i++)
{
if(isLeapYear(i))
sum+=366;
else
sum+=365;
}
return sum;
}
int Date::operator -(Date & date2)
{
return (*this).daycount()-date2.daycount();
}
Date::Date(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
void Date::show()
{
cout<<year<<"/"<<month<<"/"<<day<<endl;
}
Date Date::operator ++(int)
{
Date old=*this;
day++;
adjust();
return old;
}
Date& Date::operator ++()
{
day++;
adjust();
return *this;
}
void main()
{
Date d1(2011,12,31);
Date d2(2010,4,1);
cout<<(d1-d2)<<endl;
Date d4=d1+5;
d4.show();
Date d5=10+d2;
d5.show();
Date d6=d1++;
d6.show();
Date d7=++d1;
d7.show();
Date d8=++++d1;
d8.show();
}
运算符重载----日期类
最新推荐文章于 2023-07-23 21:17:01 发布