两个时间相加问题!
当时间输入秒数为1的时候出错,帮帮看哪里错啦!#include <iostream>
using namespace std;
class Time{
public:
Time(int h, int m, int s);
Time operator +(const Time &t2);
friend ostream & operator << (ostream & os, const Time t);
private:
int hour;
int minute;
int second;
};
Time::Time(int h, int m, int s)
{
if(h>0 && h<=23) hour = h;
else cout<<"the value of hour is invalid!"<<endl;
if(m>0 && m<=59) minute = m;
else cout<<"the value of minute is invalid!"<<endl;
if(s>0 && s<=59) second = s;
else cout<<"the value of second is invalid!"<<endl;
}
Time Time::operator +(const Time &t2)
{
int hh,mm,ss;
hh=mm=ss=0;
if((ss=(second+t2.second)) >=60 ){
ss-=60;
++minute;
}
if((mm=(minute+t2.minute)) >= 60){
mm-=60;
++hour;
}
if((hh=(hour + t2.hour)) >= 24 ){
hh-=24;
cout<<"the sum is overflowed"<<endl;
}
return Time(hh,mm,ss);
}
ostream & operator<<(ostream & os, const Time t)
{
os<<t.hour<<":"<<t.minute<<":"<<t.second;
return os;
}
int main(void)
{
Time t1(2,20,1), t2(4, 50, 59);
cout<<(t1+t2)<<endl;
system("pause");
return 0;
}