1.运算符重载,先重载加后重载减,减的操作不正确
减去后的正常时间应该0小时52分钟38秒
但是结果是1小时-7分钟-22秒
错误在哪里?应该如何改进?错误的原因是?
请输入代码
#include<iostream>
using namespace std;
class Time
{
private:
int hour,minute,second;
public:
Time(int x,int y,int z)
{hour=x;minute=y;second=z;}
Time operator+(Time c1)
{
if(second+c1.second>59)
{minute++;second-=60;}
if(minute+c1.minute>59)
{hour++;minute-=60;}
return Time(hour+c1.hour,minute+c1.minute,second+c1.second);
}
Time operator-(Time c1)
{
if(second-c1.second<0)
{minute--;second+=60;}
if(minute-c1.minute<0)
{hour--;minute+=60;}
return Time(hour-c1.hour,minute-c1.minute,second-c1.second);
}
void out()
{
cout<<hour<<" hour "<<minute<<" minute "<<second<<" second"<<endl;
}
};
int main()
{
Time a(9,27,30),b(8,34,52);
(a+b).out();
(a-b).out();
return 0;
}
巴扎黑2017-04-17 13:49:06
加减重载改成下面这样
Time operator+(Time c1)
{
int t_hour = hour;
int t_minute = minute;
int t_second = second;
if(second+c1.second>59)
{t_minute++;t_second-=60;}
if(minute+c1.minute>59)
{t_hour++;t_minute-=60;}
return Time(t_hour+c1.hour,t_minute+c1.minute,t_second+c1.second);
}
Time operator-(Time c1)
{
int t_hour = hour;
int t_minute = minute;
int t_second = second;
if(second-c1.second<0)
{t_minute--;t_second+=60;}
if(minute-c1.minute<0)
{t_hour--;t_minute+=60;}
return Time(t_hour-c1.hour,t_minute-c1.minute,t_second-c1.second);
}