第六周实践项目4————静态成员的应用

问题及代码:

/*copyright(c)2016.烟台大学计算机学院  
 * All rights reserved,  
 * 文件名称:text.Cpp  
 * 作者:吴敬超  
 * 完成日期:2016年4月5日  
 * 版本号:vc++6.0  
 *  
 * 问题描述:静态成员函数
 * 输入描述:  
 * 程序输出: 输出结果  
 */
#include<iostream>
using namespace std;
class Time
{
public:
    Time (int =0,int =0,int =0);
    void show_time();
    void add_second(int );
    void add_minute(int );
    void add_hours(int );
    static void change24();
    static void changefrom0();
private:
    static bool is_24;
    static bool from0;
    int hour;
    int minute;
    int sec;
};
Time::Time(int h,int m,int s)
{
    hour=h;
    sec=s;
    minute=m;
}
bool Time::is_24 = true;
bool Time::from0 = false;
void Time::show_time( )
{
    if (is_24)
    {
        if (from0)
        {
            cout << (hour < 10 ? "0":"") << hour << ':' \
            << (minute < 10 ? "0":"") << minute << ':' << (sec < 10 ? "0":"") << sec << endl;
        }
        else
        {
            cout << hour << ':' << minute << ':' << sec << endl;
        }
    }
    else
    {
        if (from0)
        {
            cout << (hour < 10||(hour - 12 >=0 && hour - 12 < 10) ? "0":"") << (hour > 12 ? hour-12 : hour) << ':' << (minute < 10 ? "0":"") << minute << ':' << (sec < 10 ? "0":"") << sec << ' '  << (hour > 11 ? "pm" : "am") << endl;
        }
        else
        {
            cout << (hour > 12 ? hour-12 : hour) << ':'<< minute<< ':' << sec << ' ' << (hour > 11 ? "pm" : "am") << endl;
        }
    }
}
void Time::add_second(int s)
{
    sec+=s;
    sec=s%60;
    add_minute(s / 60);
}
void Time::add_minute(int m)
{
    minute+=m;
    minute=m%60;
    add_hours(m / 60);
}
void Time::add_hours(int h)
{
    h=hour+h;
    hour=h%24;
}
void Time::change24()
{
    is_24 = !is_24;

    if (is_24)
        cout << "已切换为24小时制。" << endl;
    else
        cout << "已切换为12小时制。" << endl;
}
void Time::changefrom0()
{
    from0 = !from0;

    if (from0)
        cout << "已切换为前导0输出。" << endl;
    else
    cout << "已切换为非前导0输出。" << endl;
}
int main()
{
    Time t1(23,14,25),t2(8,45,6);
    cout<<"24小时制,不前导0"<<endl;
    cout<<"t1是:";
    t1.show_time();
    cout<<"t2是:";
    t2.show_time();
    t1.add_hours(10);
    t2.add_hours(10);
    Time::changefrom0();
    cout<<"10小时后,切换是否前导0"<<endl;
    cout<<"t1是:";
    t1.show_time();
    cout<<"t2是:";
    t2.show_time();
    t1.change24();
    cout<<"换一种制式"<<endl;
    cout<<"t1是:";
    t1.show_time();
    cout<<"t2是:";
    t2.show_time();
    cout<<endl;
}

运行结果:

第六周实践项目4————静态成员的应用_第1张图片

你可能感兴趣的:(第六周实践项目4————静态成员的应用)