定义一个时间类time,内有数据成员hour,minute,second,另有成员函数:构造函数用于初始化数据成员,输出函数,运算符重载+(加号),。编写主函数:创建时间对象,再输入秒数 n,通过运算符重载+(减号),计算该时间再过 n 秒后的时间值,时间的表示形式为时:分:秒,超过 24 时从 0 时重新开始计时。
1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 5 class Time //定义Time类 6 { 7 private: 8 int hour,minute,second; //私有变量hour,minute,second 9 public: 10 friend Time operator + (Time &T1,Time &T2); //友元函数重载 + 11 friend Time operator - (Time &T1,Time &T2); //友元函数重载 - 12 friend istream& operator >> (istream &input,Time &T); //友元函数重载 >> 输入流 13 friend ostream& operator << (ostream &output,Time &T); //友元函数重载 << 输出流 14 Time(){}; //默认构造函数 15 Time(int h,int m,int s):hour(h),minute(m),second(s){}; //构造函数 16 bool getEnd(void); //检查是否为end 17 }; 18 19 Time operator + (Time &T1,Time &T2) 20 { 21 Time T(0,0,0); //新建对象用于函数的返回值 22 if(T2.hour<=0&&T2.minute<=0&&T2.second<=0) //如果T2为负 23 { 24 Time T2_tmp(0,0,0); 25 T2_tmp.hour=abs(T2.hour),T2_tmp.minute=abs(T2.minute),T2_tmp.second=abs(T2.second); 26 T=T1-T2_tmp; 27 return T; 28 } 29 T.second=(T1.second+T2.second<60)?(T1.second+T2.second):(T.minute++,T1.second+T2.second-60); //时分秒的相加 30 T.minute=(T1.minute+T2.minute+T.minute<60)?(T.minute+T1.minute+T2.minute):(T.hour++,T.minute+T1.minute+T2.minute-60); 31 T.hour=(T1.hour+T2.hour+T.hour<24)?(T.hour+T1.hour+T2.hour):(T.hour-=24,T.hour+T1.hour+T2.hour); 32 return T; 33 } 34 35 Time operator - (Time &T1,Time &T2) 36 { 37 Time T(0,0,0); 38 T.second=(T1.second>=T2.second)?(T1.second-T2.second):(T.minute--,T1.second-T2.second+60); //时分秒的相加 39 T.minute=(T1.minute+T.minute>=T2.minute)?(T1.minute+T.minute-T2.minute):(T.hour--,T1.minute+T.minute-T2.minute+60); 40 T.hour=(T1.hour+T.hour>=T2.hour)?(T1.hour+T.hour-T2.hour):(T.hour+=24,T1.hour+T.hour-T2.hour); 41 return T; 42 } 43 44 istream& operator >> (istream &input,Time &T) //重载Time类的输入流 45 { 46 input>>T.hour>>T.minute>>T.second; 47 return input; //返回值 输入流类型变量 48 } 49 50 ostream& operator << (ostream &output,Time &T) //重载Time类的输出流 51 { 52 output<<"time:"<<T.hour<<":"<<T.minute<<":"<<T.second; 53 return output; //返回值 输出流类型变量 54 } 55 56 bool Time::getEnd(void) 57 { 58 if(!hour&&!minute&&!second) return false; 59 else return true; 60 } 61 62 int main() 63 { 64 Time T; 65 int S; 66 cin>>T>>S; //输入Time T(调用Time类的输入流)和int S 67 while(T.getEnd()||S) //判断是否为末尾 68 { 69 int hh,mm,ss; 70 ss=S%60,mm=((S-ss)/60)%60,hh=((((S-ss)/60)-mm)/60)%24; //将输入的秒转化为Time类 71 Time T_tmp(hh,mm,ss); 72 T=T+T_tmp; 73 cout<<T<<endl; //输出Time T(调用Time类的输出流) 74 cin>>T>>S; 75 } 76 return 0; 77 }