#include <iostream>
using namespace std;
class Time
{
public:
Time(int hour = 0 , int minute = 0 , int second = 0);
void getTime()
{
printf("%02d:%02d:%02d\n",hour,minute,second);
}
void setHour( int a )
{
hour = a;
}
void setMinute( int b )
{
minute = b;
}
void setSecond( int c )
{
second = c;
}
// 重载 + 运算符,用于把两个 Box 对象相加
Time operator+(const Time& b)
{
Time box;
box.hour = this->hour + b.hour;
box.minute = this->minute + b.minute;
box.second = this->second + b.second;
if(0<=box.hour&&box.hour<24&&0<=box.minute&&box.minute<=60&&0<=box.second&&box.second<60)
{
return box;
}
else
{
if(box.second >= 60)
{
box.minute = box.minute + box.second/60;
box.second = box.second%60;
}
if(box.minute >= 60)
{
box.hour = box.hour + box.minute/60;
box.minute = box.minute%60;
}
if(box.hour>=24)
{
box.hour = box.hour%24;
}
return box;
}
}
Time operator-(const Time& b)
{
Time box;
box.hour = this->hour - b.hour;
box.minute = this->minute - b.minute;
box.second = this->second - b.second;
if(box.second < 0)
{
box.second = 60 + box.second;
box.minute--;
}
if(box.minute < 0)
{
box.minute = 60 + box.minute;
box.hour = box.hour-1;
}
if(box.hour < 0)
{
box.hour = 24 + box.hour;
}
return box;
}
Time& operator ++ ();
Time operator ++ (int);
Time& operator -- ();
Time operator -- (int);
private:
int hour; // 长度
int minute; // 宽度
int second; // 高度
};
Time::Time(int hout , int minute , int second)
{
if(0<=hour&&hour<24&&0<=minute&&minute<=60&&0<=second&&second<60)
{
this->hour = hour;
this->minute = minute;
this->second = second;
}
else
{
if(second >= 60)
{
this->second = second%60;
minute = minute + second/60;
}
else
{
this->second = second;
}
if(minute >= 60)
{
this->minute = minute%60;
hour = hour + minute/60;
}
else
{
this->minute = minute;
}
if(hour>=24)
{
this->hour = hour%24;
}
else
{
this->hour = hour;
}
}
}
Time &Time::operator ++()
{
second++;
if(second >= 60)
{
second-=60;
minute++;
}
if(minute>=60)
{
minute-=60;
hour = (hour+1)%24;
}
if(hour >= 24)
{
hour = hour%24;
}
return *this;
}
Time Time::operator ++(int)
{
Time old = *this;
++(*this);
return old;
}
Time &Time::operator --()
{
second--;
if(second < 0)
{
second = 60 + second;
minute--;
}
if(minute < 0)
{
minute = 60 + minute;
hour = hour-1;
}
if(hour < 0)
{
hour = 24+hour;
}
return *this;
}
Time Time::operator --(int)
{
Time old = *this;
--(*this);
return old;
}
// 程序的主函数
int main( )
{
Time Box1;
Time Box2;
Time Box3;
int x1,x2,x3;
cin >> x1 >> x2 >> x3;
Box1.setHour(x1);
Box1.setMinute(x2);
Box1.setSecond(x3);
cin >> x1 >> x2 >> x3;
Box2.setHour(x1);
Box2.setMinute(x2);
Box2.setSecond(x3);
Box1 = Box1 + (Box2++);
Box1.getTime();
Box1 = Box1 - Box2;
Box1.getTime();
Box3 = (++Box2);
Box3.getTime();
Box2 = Box2 + (Box1--);
Box2.getTime();
Box3 = (--Box1);
Box3.getTime();
Box2 = Box2 - Box1;
Box2.getTime();
return 0;
}
时钟类运算符重载
最新推荐文章于 2023-05-09 19:36:10 发布