一个时间类,采用运算符重载的方法实现时间的加、减运算,以及时间的显示。编写主函数进行测试。
时间: 2024-05-30 20:16:04 浏览: 12
#include<iostream>
using namespace std;
class Time
{
private:
int hour;
int minute;
public:
Time(int h=0,int m=0)
{
hour=h;
minute=m;
}
friend Time operator+(const Time& t1,const Time& t2);
friend Time operator-(const Time& t1,const Time& t2);
friend ostream& operator<<(ostream& os,const Time& t);
};
Time operator+(const Time& t1,const Time& t2)
{
Time sum;
sum.minute=(t1.minute+t2.minute)%60;
sum.hour=(t1.hour+t2.hour)+(t1.minute+t2.minute)/60;
return sum;
}
Time operator-(const Time& t1,const Time& t2)
{
Time diff;
int tot1=t1.hour*60+t1.minute;
int tot2=t2.hour*60+t2.minute;
diff.hour=(tot1-tot2)/60;
diff.minute=(tot1-tot2)%60;
return diff;
}
ostream& operator<<(ostream& os,const Time& t)
{
os<<t.hour<<" hours "<<t.minute<<" minutes"<<endl;
return os;
}
int main()
{
Time t1(2,45),t2(1,30),t3;
t3=t1+t2;
cout<<"t1+t2="<<t3;
t3=t1-t2;
cout<<"t1-t2="<<t3;
return 0;
}
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)