- #include <iostream>
- #include <cstdio>
- using std::cout;
- using std::cin;
- using std::endl;
- class Time
- {
- public:
- Time(int h = 0,int m = 0,int s = 0):hour(h),minute(m),sec(s){};
- void set_time();//设置时间
- void show_time();//显示时间
- void add_seconds(int);//增加秒
- void add_minutes(int);//增加分钟
- void add_hours(int);//增加小时
- void check();//检查时间格式
- static void change24();//用于切换12小时制和24小时制,ok
- static void changefrom0();//根据from0切换是否前导0,ok
- private:
- bool is_time(int ,int ,int);
- static bool is_24;//为true,24小时制,否则12小时制
- static bool from0;//为true,前导0,否则,不前导0
- int hour = 0;
- int minute = 0;
- int sec = 0;
- };
- bool Time::is_24 = true;
- bool Time::from0 = false;
- void Time::check()
- {
- if(!is_24 && hour > 11)
- hour = hour%12;
- }
- void Time::change24()
- {
- int flag;
- cout << "1:24小时制\n2:12小时制" << endl;
- cin >> flag;
- is_24 = (flag == 1 ? true:false);
- }
- void Time::changefrom0()
- {
- int flag;
- cout << "1:有前导0\n2:无前导0" << endl;
- cin >> flag;
- from0 = (flag == 1 ? true:false);
- }
- void Time::show_time()
- {
- if(is_24)
- if(from0)
- printf("%02d:%02d:%02d\n",hour,minute,sec);
- else
- printf("%d:%d:%d\n",hour,minute,sec);
- else
- if(from0)
- printf("%02d:%02d:%02d\n",hour,minute,sec);
- else
- printf("%d:%d:%d\n",hour,minute,sec);
- }
- void Time::add_seconds(int s)
- {
- sec = sec + s;
- if(sec > 59)
- {
- add_minutes(sec/60);
- sec = sec%60;
- }
- }
- void Time::add_minutes(int m)
- {
- minute = minute + m;
- if(minute > 59)
- {
- add_hours(minute/60);
- minute = minute%60;
- }
- }
- void Time::add_hours(int h)
- {
- hour = hour + h;
- if(is_24)
- {
- if(hour > 23)
- hour = hour%24;
- }
- else
- if(hour > 11)
- hour = hour%12;
- }
- void Time::set_time()
- {
- cout << "默认时间格式为24小时制,时间不足两位数字时无前导0" << endl;
- cout << "请输入时间(格式hh:mm:ss)";
- char c1,c2;
- while(1)
- {
- cin >> hour >> c1 >> minute >> c2 >> sec;
- if(c1 != ':' || c2 != ':')
- {
- cout << "格式不正确重输" << endl;
- cin.clear();
- cin.sync();
- }
- else if(!is_time(hour,minute,sec))
- cout << "时间非法,请重新输入" << endl;
- else
- break;
- }
- }
- bool Time::is_time(int h, int m,int s)
- {
- if(is_24)
- if(h < 0 || h > 23 || m <0 || m > 60 || s <0 || s > 60)
- return false;
- else
- return true;
- else
- if(h < 0 || h > 11 || m <0 || m > 60 || s <0 || s > 60)
- return false;
- else
- return true;
- }
- int main()
- {
- Time t1;
- t1.show_time();
- t1.set_time();
- t1.show_time();
- t1.changefrom0();
- t1.show_time();
- t1.add_seconds(100);
- t1.add_minutes(100);
- t1.add_hours(15);
- t1.show_time();
- t1.change24();
- t1.check();
- t1.show_time();
- return 0;
- }
静态成员的应用
最新推荐文章于 2017-10-24 21:30:52 发布