日期类与时间类定义(运算符重载应用)
日期类定义(运算符重载应用):
class Data
{
int year;
int month;
int day;
public:
Data(){};
Data(int year1,int month1,int day1):year(year1),month(month1),day(day1){};
friend ostream&operator<<(ostream&os,const Data&d);
friend istream&operator>>(istream&is,Data&d);
bool operator<(const Data &d)const
{return year!=d.year?year<d.year:month!=d.month?month<d.month:day<d.day;}
int operator-(Data d)
{
if(year<d.year||(year==d.year&&month<d.month)||(year==d.year&&month==d.month&&day<d.day))
return -1;
int m[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int count=0;
int a=d.year,b=d.month,c=d.day;
while(1)
{
if(this->year==a&&this->month==b&&this->day==c) break;
if(c==m[b]){
c=1;
if(b==12)
{
b=1;
a++;
}
else b++;
}
else c++;
count++;
}
return count;
}
Data operator+ (int x)
{
int m[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
while(x--)
{
if(day==m[month])
{
day=1;
if(month==12)
{
year++;
month=1;
}
else month++;
}
else day++;
}
return *this;
}
};
istream&operator>>(istream&is,Data&d)
{
while(1)
{
is>>d.year>>d.month>>d.day;
if(d.year<1900||d.year>2019||d.month<1||d.month>12||d.day<1||d.day>31);
else break;
}
return is;
}
ostream&operator<<(ostream&os,const Data&d)
{
os<<d.year<<" "<<d.month<<" "<<d.day;
return os;
}
时间类定义(运算符重载应用):
class Time
{
int year,month,day,hour,min;
string s;
public:
Time() {};
~Time() {};
Time(int year1,int month1 ,int day1,int hour1,int min1):year(year1),month(month1),day(day1),hour(hour1),min(min1) {};
friend istream& operator>>(istream&,Time&t);
friend ostream& operator<< (ostream&,const Time&t);
int operator- (Time t)
{
if((year<t.year)||(year==t.year&&month<t.month)||(year==t.year&&month==t.month&&day<t.day)||(year==t.year&&month==t.month&&day==t.day&&hour<t.hour)||year==t.year&&month==t.month&&day==t.day&&hour==t.hour&&min<t.min)
return -1;
int countyear=0;
int countmonth=0;
int countday=0;
int counthour=0;
int countmin=0;
int m[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
while(1)
{
if(this->year==t.year&&this->month==t.month&&this->day==t.day&&hour==t.hour&&min==t.min) break;
if(t.min==60)
{
t.hour++;
counthour++;
t.min=0;
if(t.hour==24)
{
t.day++;
countday++;
t.hour=0;
if(t.day>m[t.month])
{
t.month++;
countmonth++;
t.day=1;
if(t.month>12)
{
t.year++;
countyear++;
t.month=1;
}
}
}
}
else {t.min++;countmin++;}
}
return countmin;
}
bool operator< (const Time&t)const
{
return year!=t.year?year<t.year:month!=t.month?month<t.month:day!=t.day?day<t.day:hour!=t.hour?hour<t.hour:min<t.min;
}
bool operator== (const Time&t)const
{
return year==t.year&&month==t.month&&day==t.day&&hour==t.hour&&min==t.min;
}
};
istream&operator>>(istream&in,Time&t)
{
while(1)
{
in>>t.year>>t.month>>t.day>>t.hour>>t.min;
if(t.year>2000&&t.year<=2019&&t.month>=1&&t.month<=12&&t.day>=1&&t.day<=31&&t.hour>=0&&t.hour<=23&&t.min>=0&&t.min<60)
break;
else cout<<"Time error,请重试:"<<endl;
}
return in;
}
ostream&operator<<(ostream&out,const Time&t)
{
out<<t.year<<" "<<t.month<<" "<<t.day<<" "<<t.hour<<" "<<t.min;
return out;
}