#include <iostream.h>
class Time
{
int hour; //时数
int minute; //分数
int second; //秒数
public:
//Time() {}; //构造函数
Time(int h=0,int m=0,int s=0) //重载构造函数
{
hour=h;minute=m;second=s;
}
void sethour(int h) { hour=h;}
void setminute(int m) {minute=m;}
void setsecond(int s) {second=s;}
int gethour() {return hour;}
int getminute() {return minute;}
int getsecond() {return second;}
Time &operator+(Time);
Time &operator-(Time);
void disp()
{
cout << hour << ":" << minute << ":" << second << endl;
}
};
Time &Time::operator +(Time t)
{
int carry,hh,mm,ss;
ss=getsecond()+t.getsecond();
if(ss>60)
{
ss-=60;
carry=1; //秒数大于69,则需进一位
}
else
carry=0;
mm=getminute()+t.getminute()+carry;
if(mm>60)
{
mm-=60;
carry=1; //分数大于69,则需进一位
}
else carry=0;
hh=gethour()+t.gethour()+carry;
if(hh>24)
hh-=24;
//static Time result(hh,mm,ss); //构造一个静态对象result
return *this;//result;
}
Time &Time::operator -(Time t)
{
int borrow,hh,mm,ss;
ss=getsecond()-t.getsecond();
if(ss<0)
{
ss+=60;
borrow=1; //秒数小于0,则需要从分数借一位
}
else
borrow=1;
mm=getminute()-t.getsecond()-borrow;
if(mm<0)
{
mm+=60;
borrow=1; //秒数小于0,则需要从分数借一位
}
else
borrow=0;
hh=gethour()-t.getsecond()-borrow;
if(hh<0)
{
hh+=24;
//static Time result(hh,mm,ss); //构造一个静态对象result
return *this;
}
}
void main()
{
Time now(2,24,39);
Time start(0,17,55);
Time t1=now-start,t2=now+start;
cout << "时间1:";now.disp();
cout << "时间2:";start.disp();
cout << "相差:";t1.disp();
cout << "相加:";t2.disp();
}