C++编程 有关运算符重载

来源:百度知道 编辑:UC知道 时间:2024/06/07 04:34:44
为Time类重载“+”运算符,实现在某一个时间上(时,分,秒)加上一秒

#include <iostream.h>

class Time
{
public:
Time(int hh=0,int mm=0,int ss=0):h(hh),m(mm),s(ss){}
Time operator +(int add);
friend ostream & operator <<(ostream & os,const Time & t);
private:
int h;
int m;
int s;
};

Time Time::operator +(int add)
{
s+=add;
if(s>=60)
{
m+=s/60;
s%=60;
if(m>=60)
{
h=(h+m/60)%24;
m%=60;
}
}
return * this;
}

ostream & operator <<(ostream & os,const Time & t)
{
return os<<t.h<<":"<<t.m<<":"<<t.s;
}

int main()
{
cout<<"输入h m s"<<endl;
int h,m,s;
cin>>h>>m>>s;
Time t(h,m,s);
cout<<"输入需要加的秒数:"<<endl;
int sec_add;
cin>>sec_add;
cout&