问题及代码
/*
*ALL rights reserved.
*文件名称: 初学对象2
*作者:李长鸿
*完成时间:2015.3.22
*问题描述:时间类问题
*/
#include <iostream>
using namespace std;
class Time
{
public:
void add_a_sec(); //增加1秒钟
void add_a_minute(); //增加1分钟
void add_an_hour();
void set_time( );
void show_time( );
private:
bool is_time(int, int, int); //这个成员函数设置为私有的,是合适的,请品味
int hour;
int minute;
int sec;
};
void Time::set_time( )
{
char c1,c2;
cout<<"请输入时间(格式hh:mm:ss)";
while(1)
{ cin>>hour>>c1>>minute>>c2>>sec;
if(c1!=':'||c2!=':')
cout<<"格式不正确,请重新输入"<<endl;
else if (!is_time(hour,minute,sec))
cout<<"时间非法,请重新输入"<<endl;
else
break;
}
}
void Time::add_a_sec()
{
sec++;
if(sec==60)
{
sec=0;
add_a_minute();
}
}
void Time::add_a_minute()
{
minute++;
if(minute==60)
{
minute=0;
add_an_hour();
}
}
void Time::add_an_hour()
{
hour++;
if(hour==24)
hour=0;
}
void Time::show_time( )
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
bool Time::is_time(int h,int m, int s)
{
if (h<0 ||h>24 || m<0 ||m>60 || s<0 ||s>60)
return false;
return true;
}
int main( )
{
Time t1;
t1.set_time( );
t1.add_a_sec(); //增加1秒钟
t1.show_time( );
return 0;
}
总结:主函数调用时,把三个增加的都写上去了,结果时分秒都加了一。这是在老师讲了之后写的,相对来说要少那么些思考。。。。