第五周项目4-静态成员应用

来源:互联网 发布:宁波网络继续教育 编辑:程序博客网 时间:2024/05/18 09:59
/*  *Copyright (c) 2014, 烟台大学计算机学院  *All rights reserved.  *文件名称:week5-4.cpp  *作者:高赞  *完成日期:2015年 4 月 8 日  *版本号:v1.0  *  *  */ #include <iostream>#include <iomanip>using namespace std;class Time{public:    Time(int h=0,int m=0,int s=0):hour(h),minute(m),sec(s){}    void show_time( ); //根据is_24和from0,输出适合形式-20:23:5/8:23:5 pm/08:23:05 pm    void add_seconds(int); //增加n秒钟    void add_minutes(int); //增加n分钟    void add_hours(int); //增加n小时    static void change24();  //改变静态成员is_24,在12和24时制之间转换    static void changefrom0();   //改变静态成员from0,切换是否前导0private:    static bool is_24; //为true时,24小时制,如20:23:5;为flase,12小时制,显示为8:23:5 pm    static bool from0; //为true时,前导0,8:23:5显示为08:23:05    int hour;    int minute;    int sec;};//下面写出静态成员的初始化及各成员函数的定义……bool Time::is_24=true;bool Time::from0=false;int main(){    Time t(1,2);    cout<<"此刻时间(24小时制):";    t.show_time();    cout<<endl<<"61秒后(前导0):";    t.add_seconds(61);    t.changefrom0();    t.show_time();    cout<<endl<<"14小时后(12小时制):";    t.add_hours(14);    t.changefrom0();    t.change24();    t.show_time();    cout<<endl<<"59分钟后(前导0,24小时制):";    t.add_minutes(59);    t.changefrom0();    t.change24();    t.show_time();    return 0;}void Time::show_time(){    string t;    if(is_24==false)    {        if(hour>=12)        {            t=" pm";        }        else t=" am";        if(from0==true)            cout<<setfill('0')<<setw(2)<<(hour%12)<<":"<<setw(2)<<minute<<":"<<setw(2)<<sec<<t;        else cout<<(hour%12)<<":"<<minute<<":"<<sec<<t;    }    else    {        if(from0==true)            cout<<setfill('0')<<setw(2)<<hour<<":"<<setw(2)<<minute<<":"<<setw(2)<<sec;        else cout<<hour<<":"<<minute<<":"<<sec;    }}void Time::add_seconds(int n){    n+=sec;    sec=n%60;    add_minutes(n/60);}void Time::add_minutes(int n){    n+=minute;    minute=n%60;    add_hours(n/60);}void Time::add_hours(int n){    n+=hour;    hour=n%24;}void Time::change24(){    if(is_24==true)        is_24=false;    else is_24=true;}void Time::changefrom0(){    if(from0==true)        from0=false;    else from0=true;}


 

看起来似乎麻烦,但实际比较简单,只要控制好输出形式就行了。

0 0
原创粉丝点击