24.实现类Time的两个函数,其中构造函数Time按照参数h、m、s的值初始化数据成员hour、min、sec,如果h、m、s的值合法则直接初始化,否则将对应的数据成员初始化为0。合法值范围分别为0<=h<=23、0<=m<=59、0<=s<=59。函数add实现时间和整数(秒相加,例如11:11:11 + 100 = 11:12:51,相加后要保证时间数值的合法性。 样例输入:60 样例输出:12:23:34 + 60 = 12:24:34
#include <iostream>
using namespace std;
class Time {
public:
Time(int h=0, int m=0, int s=0);
void add(int ss);
int geth() {return hour;}
int getm() {return min;}
int gets() {return sec;}
private:
int hour, min, sec;
};
/**********Program**********/
Time::Time(int h, int m, int s) {
if (h >= 0 && h <= 23 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
hour = h;
min = m;
sec = s;
} else {
hour = 0;
min = 0;
sec = 0;
}
}
void Time::add(int ss) {
sec += ss;
while (sec >= 60) {
sec -= 60;
min++;
}
if (min >= 60) {
min -= 60;
hour++;
}
if (hour >= 24) {
hour -= 24;
}
}
/********** End **********/
int main()
{
Time now(12,23,34);
int ss;
cin>>ss;
now.add(ss);
cout<<"12:23:34 + "<<ss<<" = "
<<now.geth()<<":"<<now.getm()<<":"<<now.gets()<<endl;
}