#include <iostream>
using namespace std;
class times
{
public:
times()
{
h = -1;
m = -1;
s = -1;
}
times(int h, int m, int s)
{
this->h = h;
this->m = m;
this->s = s;
}
void show()
{
cout << h << ":" << m << ":" << s << endl;
}
times operator+(times T) //+
{
times res;
res.h = T.h + h;
res.m = T.m + m;
res.s = T.s + s;
// cout<<T.s<<" "<<s<<" "<<res.s<<endl;
if (res.s > 60)
{
res.s = res.s % 60;
res.m = res.m + 1;
}
if (res.m > 60)
{
res.m = res.m % 60;
res.h = res.h + 1;
}
return res;
}
times operator-(times T) //-
{
times res;
res.h = h - T.h;
res.m = m - T.m;
res.s = s - T.s;
// cout<<T.s<<" "<<s<<" "<<res.s<<endl;
if (res.s < 0)
{
res.s = (res.s + 60) % 60;
res.m = res.m - 1;
}
if (res.m < 0)
{
res.m = (res.m + 60) % 60;
res.h = res.h - 1;
}
if (res.h < 0)
{
res.h = 0;
}
return res;
}
times operator+(int n) //+
{
this->s = s + n;
if (this->s > 60)
{
this->s = this->s % 60;
this->m = this->m + 1;
}
if (this->m > 60)
{
this->m = this->m % 60;
this->h = this->h + 1;
}
return *this;
}
times operator-(int n) //-
{
this->s = s - n;
if (this->s < 0)
{
this->s = (this->s + 60) % 60;
this->m = this->m - 1;
}
if (this->m < 0)
{
this->m = (this->m + 60) % 60;
this->h = this->h - 1;
}
if (this->h < 0)
{
this->h = 0;
}
return *this;
}
int &operator[](int i)
{
if (i == 0)
{
return this->s;
}
else if (i == 1)
{
return this->m;
}
else if (i == 2)
{
return this->h;
}
}
int h;
int m;
int s;
};
int main(int argc, const char *argv[])
{
times T0(15, 34, 30);
T0.show();
int sec = T0[0];
cout << sec << endl;
T0[0] = 55;
cout << T0[0] << endl;
times T1(14, 01, 59);
times T3;
// T3=T0+T1;
// T3.show();
T3 = T0 - T1;
T3.show();
T3 = T3 + 10;
T3.show();
T3 = T3 - 10;
T3.show();
return 0;
}
C++第四天
本文介绍了一个C++编程中的自定义时间类times,包含了时间对象的构造、显示、加法和减法运算,以及对时间分秒的直接访问。
摘要由CSDN通过智能技术生成