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

来源:互联网 发布:淘宝联盟佣金是全店吗 编辑:程序博客网 时间:2024/05/18 09:50

 

/*  * Copyright (c) 2014, 烟台大学计算机学院  * All rights reserved.  * 文件名称:test.cpp  * 作    者:呼亚萍  * 完成日期:2015年4月8日  * 版 本 号:v1.0  *  * 问题描述:设计含有静态数据成员和成员函数的Time类。静态数据成员是类中所有的对象共有的数据,在下面的设计中,时钟要采用12小时制,还是要使用24小时制,显示时,不足两位的数字前是否前导0,都是“影响全局”的设置,适合作为类中的静态数据成员 * 程序输入:相应的函数 * 程序输出:不同形式的时间 */#include <iostream>using namespace std;class Time{public:    Time(int=0,int=0,int=0);//构造函数的初始化    void show_time();//根据is_24和from0,输出合适的形式20:23:5/8:23:5pm/08:23:5 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小时制    static bool from0;//为true时,前导0    int hour;    int minute;    int sec;};bool Time::is_24=true;bool Time::from0=false;Time::Time(int x,int y,int z):hour(x),minute(y),sec(z) {}void Time::show_time(){    int h;    if(is_24)    {        h=hour;    }    else        h=hour%12;    if(h<10&&from0)        cout<<'0';    cout<<h<<":";    if(minute<10&&from0)        cout<<'0';    cout<<minute<<":";    if(sec<10&&from0)        cout<<'0';    cout<<sec;    if(!is_24)    {        cout<<((hour<12)?"am":"pm");    }}void Time::add_seconds(int n){    sec+=n;    if(sec>59)    {        add_minutes(sec/60);        sec=sec%60;    }}void  Time::add_minutes(int n){    minute+=n;    if(minute>59)    {        add_hours(minute/60);        minute=minute%60;    }}void  Time::add_hours(int n){    hour+=n;    if(hour>23)    {        hour=hour%24;    }}void Time::change24(){    is_24=!is_24;}void Time::changefrom0(){    from0=!from0;}int main(){    Time t1(23,14,25),t2(9,14,25);    cout<<"24时制,不前导0"<<endl;    cout<<"t1是:";    t1.show_time();    cout<<endl;    cout<<"t2是";    t2.show_time();    cout<<endl;    Time::changefrom0(); //注意此处调用静态成员    cout<<"10小时后,切换至前导0";    t1.add_hours(10);    t2.add_hours(10);    cout<<endl;    cout<<"t1是:";    t1.show_time();    cout<<endl;    cout<<"t2是";    t2.show_time();    cout<<endl;    cout<<"换一种形式:"<<endl;    cout<<"t1是:";    t1.change24();    t1.show_time();    cout<<endl;    cout<<"t2是";    t2.show_time();    return 0;}


运算结果:

知识点总结:

bool语句的巧妙应用,静态函数在定义的时候不注明static,静态成员的初始化在类外进行,静态函数是大家共同享有!

学习心得:

c++程序中包含了许多巧妙的构思,继续学习。加油!

0 0