编写一个程序,其中设计一个时间类Time,用来保存时、分、秒等私有数据成员,通过重载操作符“+”实现两个时间的相加。要求将小时范围限制在大于等于0,分钟范围限制在0~59分,秒钟范围限制在0~59秒。【提示】时间类Time的参考框架如下:class Time{public :Time(int h=0,int m=0,int s=0); //构造函数Time operator+(Time&); //运算符重载函数,实现两个时间的相加void disptime(string); //输出时间函数private:int hours; //小时int minutes; //分钟int seconds; //秒钟};#includeusing namespace std;class Time { friend Time operator-(const Time& T1, const Time& T2); friend ostream& operator<<(ostream& out, Time& T); friend istream& operator>>(istream& cin, Time& T);public: Time() {}; Time(int h, int m, int s) { hour=h; minute=m; second=s; if(hour>=24) { hour=hour%24; } if(minute>=60) { hour=hour+1; minute=minute%60; } if(second>60) { minute=minute+1; second=second%60; } } Time operator+(Time& t) { Time T; if((this->hour+t.hour)>=24) { T.hour=(this->hour+t.hour)%24; } else { T.hour=this->hour+t.hour; } if((this->minute+t.minute)>=60) { T.hour+=1; T.minute=(this->minute+t.minute)%60; } else { T.minute=this->minute+t.minute; } if((this->second+t.second)>=60) { T.minute+=1; T.second=(this->second+t.second); } else { T.second=this->second+t.second; } return T; }private: int hour; int minute; int second;};Time operator-(const Time& T1, const Time& T2){ Time T(0, 0, 0); if((T1.hour-T2.hour)>=24) { T.hour=(T1.hour-T2.hour)%24; } else { T.hour=T1.hour-T2.hour; } if((T1.minute-T2.minute)>=60) { T.hour+=1; T.minute=(T1.minute-T2.minute)%60; } else { T.minute=T1.minute-T2.minute; } if((T1.second-T2.second)>=60) { T.minute+=1; T.second=(T1.second-T2.second); } else { T.second=T1.second-T2.second; } return T;}ostream& operator<<(ostream& cout, Time& T){ cout<<T.hour<<"时"<<T.minute<<"分"<<T.second<<"秒"<<endl; return cout;}istream& operator>>(istream& cin, Time& T){ Time t; char op; cin>>T.hour>>op>>T.minute>>op>>T.second; if (T.hour>=0&&T.hour;<24&&T.minute;>=0&&T.minute;<60&&T.second;>=0&&T.second;<60) { t.hour=T.hour; t.minute=T.minute; t.second=T.second; } else { cout<<"输入有误,请重新输入"<<endl; cin>>T.hour>>op>>T.minute>>op>>T.second; } return cin; return cin;}int main(){ Time t0(12, 28, 68); Time t1(28, 18, 12); Time t2(13, 75, 24); Time t3,t4; t3=t1+t2; t4=t2-t1; cout<<"t0: "<<t0<<endl; cout<<"t1: "<<t1<<endl; cout<<"t2: "<<t2<<endl; cout<<"t3 = t1 + t2: "<<t3<<endl; cout<<"t4 = t2 - t1: "<<t4<<endl; return 0;}
点赞 (10)
回复