题目:
![](https://i-blog.csdnimg.cn/blog_migrate/67b5a30873f89916e5f26a8d561fcb19.png)
代码实现:
#include<iostream>
using namespace std;
class ttime
{
public:
ttime()
{
h = 0;
m = 0;
s = 0;
}
ttime(int xh,int xm,int xs )
{
h = xh;
m = xm;
s = xs;
}
int &operator[](int i);
ttime operator+(ttime tm1);
ttime operator-(ttime tm1);
ttime operator-(int n);
ttime operator+(int i)
private:
int h;
int m;
int s;
int flag = -1;
};
int &ttime::operator[](int i)
{
if(i == 0)
{
return h;
}
else if(i == 1)
{
return m;
}
else if(i == 2)
{
return s;
}
else
{
cout<<"下标错误"<<endl;
return flag;
}
}
ttime ttime::operator+(ttime tm1)
{
ttime tm2;
tm2.s = this->s + tm1.s;
if(tm2.s >=60)
{
tm2.s -= 60;
tm2.m += 1;
}
tm2.m = this->m + tm1.m + tm2.m;
if(tm2.m>=60)
{
tm2.m -= 60;
tm2.h += 1;
}
tm2.h = this->h + tm1.h + tm2.h;
return tm2;
}
ttime ttime::operator-(ttime tm1)
{
ttime tm2;
tm2.s = this->s - tm1.s;
if(tm2.s < 0)
{
tm2.s += 60;
tm2.m -= 1;
}
tm2.m = this->m - tm1.m + tm2.m;
if(tm2.m < 0)
{
tm2.m += 60;
tm2.h -= 1;
}
tm2.h = this->h - tm1.h + tm2.h;
if(tm2.h < 0)
{
cout<<"时间不够减啦!!!"<<endl;
}
return tm2;
}
ttime ttime::operator-(int n)
{
this->s -=n;
which(1)
{
if(this->s < 0)
{
this->s += 60;
this->m -=1;
}
if(this->s > 0)
{
break;
}
}
which(1)
{
if(this->m < 0)
{
this->m += 60;
this->h -= 1;
}
if(this->m>0)
{
break;
}
}
if(this->h < 0)
{
cout<<"时间不够减啦!!!"<<endl;
}
return this;
}
ttime ttime::operator+(int i)
{
this->s += i;
which(1)
{
if(this->s >= 60)
{
this->s -= 60;
this->m += 1;
}
if(this->s <60)
{
break;
}
}
which(1)
{
if(this->m >= 60)
{
this->m -= 60;
this->h += 1;
}
if(this->m <60)
{
break;
}
}
return this;
}
int main()
{
ttime tm1(9,10,36);
ttime tm2(10,58,24);
ttime tm3 = tm1 + tm2;
ttime tm4 = tm2 - tm1;
ttime tm5 = tm4 + 120;
ttime tm6 = tm5 - 80;
cout<<"tm3: "<<tm3[0]<<"h:"<<tm3[1]<<"m:"<<tm3[2]<<"s"<<endl;
cout<<"tm4: "<<tm4[0]<<"h:"<<tm4[1]<<"m:"<<tm4[2]<<"s"<<endl;
return 0;
}