按要求添加程序
#include <iostream>
using namespace std;
class Time
{
public:
void set_time( );
void show_time( );
private:
bool is_time(int, int, int); //is_time函数仅限于类内使用,声明为private型是必要的。
//另外,请欣赏函数名的取法。函数的作用在于判断,返回值为bool型,is_time()看起来就是个一般疑问句,读起来很上口
int hour;
int minute;
int sec;
};
int main( )
{
Time t1;
Time &t2=t1; //t2为引用变量(对象),需要理解其作用
t1.set_time();
t2.show_time();
return 0;
}
void Time::set_time( ) //这段函数给出了“界面友好”型输入的范例
{
char c1,c2;
cout<<"请输入时间(格式hh:mm:ss)";
while(1)
{
cin>>hour>>c1>>minute>>c2>>sec;
if(c1!=':'||c2!=':')
cout<<"格式不正确,请重新输入"<<endl;
elseif (!is_time(hour,minute,sec))
cout<<"时间非法,请重新输入"<<endl;
else
break;
}
}
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;
}
要求:请在原类基础上,增加下列成员函数,要求前三个设计成内置函数,在main()数中增加适当的调用以展示扩充类定义后的功能(最好能一次运行)。
add_a_sec() //增加1秒钟
add_a_minute() //增加1分钟
add_an_hour() //增加1小时
提示:要考虑增加后超出取值范围的情形
程序:
#include <iostream> using namespace std; class Time { public: void set_time( ); void show_time( ); void add_a_sec();//增加1秒钟 void add_a_minute(); //增加1分钟 void add_an_hour(); //增加1小时 private: bool is_time(int, int, int); //is_time函数仅限于类内使用,声明为private型是必要的。 //另外,请欣赏函数名的取法。函数的作用在于判断,返回值为bool型,is_time()看起来就是个一般疑问句,读起来很上口 int hour; int minute; int sec; }; int main( ) { Time t1; Time &t2=t1; //t2为引用变量(对象),需要理解其作用 t1.set_time(); cout<<"现在时间是: "; t2.show_time(); t2.add_a_sec (); cout<<"增加一秒后: "; t2.show_time (); t1.add_a_minute (); cout<<"增加一分钟后: "; t1.show_time (); t1.add_an_hour (); cout<<"增加一个小时后: "; t1.show_time (); system("pause"); return 0; } void Time::set_time( ) //这段函数给出了“界面友好”型输入的范例 { cout<<"请输入时间(格式hh:mm:ss) "; while(1) { cin>>hour>> minute>> sec; if (!is_time(hour,minute,sec)) cout<<"时间非法,请重新输入"<<endl; else break; } } 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; } void Time::add_a_sec() //增加1秒钟 { ++sec; if(sec>59) ++minute; } void Time::add_a_minute() //增加1分钟 { ++minute; if(minute>59) ++hour; } void Time::add_an_hour() //增加1小时 { ++hour; if(hour>23) hour=0; }