编写一个时间类,采用运算符重载的方法实现时间的 加、减运算,以及时间的显示。编写主函数进行测 试。
时间: 2024-05-19 21:12:55 浏览: 81
运算符重载,实现时间的加减
4星 · 用户满意度95%
#include<iostream>
using namespace std;
class Time{
private:
int hour;
int minute;
int second;
public:
Time(int h=0,int m=0,int s=0):hour(h),minute(m),second(s){} //构造函数
void display() const{ //显示时间
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
Time operator+(const Time &t) const{ //加法运算符重载
Time sum;
sum.second=second+t.second;
sum.minute=minute+t.minute+sum.second/60;
sum.second%=60;
sum.hour=hour+t.hour+sum.minute/60;
sum.minute%=60;
sum.hour%=24;
return sum;
}
Time operator-(const Time &t) const{ //减法运算符重载
Time diff;
int tot1=hour*3600+minute*60+second;
int tot2=t.hour*3600+t.minute*60+t.second;
if(tot1>=tot2){
int tot=tot1-tot2;
diff.hour=tot/3600;
diff.minute=(tot-diff.hour*3600)/60;
diff.second=tot%60;
}else{
int tot=tot2-tot1;
diff.hour=tot/3600;
diff.minute=(tot-diff.hour*3600)/60;
diff.second=tot%60;
diff.hour=24-diff.hour;
diff.minute=60-diff.minute;
diff.second=60-diff.second;
}
return diff;
}
};
int main(){
Time t1(2,30,0);
Time t2(1,50,45);
Time t3=t1+t2;
Time t4=t1-t2;
t1.display();
t2.display();
t3.display();
t4.display();
return 0;
}
阅读全文