给出下面的基类Time的框架如下:
class Time
{
protected:
}
建立一个派生类Time_12hours,用于表示十二进制时间,增加以下成员数据:
string type;//标识为12进制时间,type=”12-hours-time”
string interval;//标识为AM或者PM,interval=”AM”或interval=”PM”
增加以下成员函数: void operator++();
void operator--();建立一个派生类Time_24hours,用于表示二十四进制时间,增加以下成员数据:
string type;//标识为24进制时间,type=”24-hours-time”增加以下成员函数:
void operator++(); void operator--();生成上述类并编写主函数,根据输入的初始时间信息、自增或者自减类型、自增或者自减次数,输出其最后时间信息。
输入格式:测试输入包含多个测试用例,一个测试用例为一行,每行共五个数字,第一个数字为进制,121表示输入为12进制AM时间,122表示输入为12进制PM时间,输入为24表示输入为24进制时间,第二个数字为hour,第三个数字为minute,第四个数字为second,第五个字符为运算类型,+表示自增,-表示自减,第六个数字为运算次数,0表示测试用例结束。
输入样例:
121 11 59 59 + 3
24 11 59 59 + 3
122 11 59 59 + 3
122 00 00 00 - 3
121 00 00 00 - 5
24 00 00 00 - 1
0
输出样例:
PM 00:00:02
12:00:02
AM 00:00:02
AM 11:59:57
PM 11:59:55
23:59:59
参考代码:
#include<iostream>
#include<iomanip>
using namespace std;
//建立Time基类
class Time{
protected:
int second;
int minute;
int hour;
int total;
public:
void operator ++ ();
void operator -- ();
friend istream& operator >>(istream& , Time& );
};
istream& operator >> (istream& set, Time& x){
set>> x.hour>> x.minute>> x.second;
x.total = (x.hour*60+ x.minute)*60 + x.second;
return set;
}
void Time::operator ++(){
total++;
second = total%60;//对60秒取余数
minute = total/60%60;//换为分对60分取余数
hour = total/3600%24;//换为小时对24小时取余数
}
void Time::operator --(){
if(total==0) total=86400;//到前一天,保证sum大于零
total--;
second = total%60;
minute = total/60%60;
hour = total/3600%24;
}
//建立Time_12hours
class Time_12hours:public Time{
private:
string type;//12-hours-time
string interval;//AM ro PM1
public:
void set(int x){if(x == 122) total += 43200;};
void operator --(){Time::operator --();};
void operator ++(){Time::operator ++();};
friend ostream& operator <<(ostream& ,Time_12hours &);
};
ostream& operator <<(ostream& put,Time_12hours &x)
{
x.type="12-hours-time ";
if(x.hour>=12)
{
x.interval="PM ";
x.hour-=12;
}
else
{
x.interval="AM ";
}
put <<x.interval
<<setiosflags(ios::right)<<setfill(\'0\')
<<setw(2)<<x.hour<<":"
<<setw(2)<<x.minute<<":"
<<setw(2)<<x.second<<endl;
}
//建立Time_24hours
class Time_24hours:public Time{
string type;
public:
void operator ++(){Time::operator ++();};
void operator --(){Time::operator --();};
friend ostream& operator <<(ostream& , Time_24hours &);
};
ostream& operator <<(ostream& put, Time_24hours& x){
put <<setiosflags(ios::right)<<setfill(\'0\')
<<setw(2)<<x.hour<<":"
<<setw(2)<<x.minute<<":"
<<setw(2)<<x.second<<endl;
}
int main(){
Time_12hours t12;
Time_24hours t24;
int type;
char flag;
int n;
while( cin>>type )
{
if( type == 0 )break;
else if( type >100 )
{
cin>>t12;
t12.set(type);
getchar();
cin>>flag>>n;
if(flag==\'+\')
while(n--)
++t12;
else
while(n--)
--t12;
cout<<t12;
}
else
{
cin>>t24;
getchar();
cin>>flag>>n;
if(flag == \'+\')
while(n--)
++t24;
else
while(n--)
--t24;
cout<<t24;
}
}
return 0;
}