/*
* 程序的版权和版本声明部分
* Copyright (c)2012, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: 时间———静态成员应用.cpp
* 作者:王昕彤
* 完成日期: 2013年 4 月 12 日
* 版本号: v1.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: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,切换是否前导0
private:
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;
};
//下面写出静态成员的初始化及各成员函数的定义……
int main( )
{
cout<<"24小时制,前导0:"<<endl;
Time t1(23,14,25),t2(8,45,6);
t1.show_time();
t2.show_time();
cout<<"12小时制,前不导0:"<<endl;
t2.change24();
t2.changefrom0();
t2.show_time();
cout<<"10小时后,切换是否导0:"<<endl;
Time::changefrom0();
t1.add_hours(10);
t1.show_time();
return 0;
}
Time::Time(int h,int m,int s)
{
hour=h;
minute=m;
sec=s;
}
void Time::show_time( )
{
if(is_24==0&&from0==0)
{
if(hour>12)
{
hour=hour%12;
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
else
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
}
if(is_24==1&&from0==1)
{
if(hour<10&&minute<10&&sec<10)
cout<<"0"<<hour<<":"<<"0"<<minute<<":"<<"0"<<sec<<endl;
else if(hour<10&&minute<10)
cout<<"0"<<hour<<":"<<"0"<<minute<<":"<<sec<<endl;
else if(minute<10&&sec<10)
cout<<hour<<":"<<"0"<<minute<<":"<<"0"<<sec<<endl;
else if(hour<10&&sec<10)
cout<<"0"<<hour<<":"<<minute<<":"<<"0"<<sec<<endl;
else if(hour<10)
cout<<"0"<<hour<<":"<<minute<<":"<<sec<<endl;
else if(minute<10)
cout<<hour<<":"<<"0"<<minute<<":"<<sec<<endl;
else if(sec<10)
cout<<hour<<":"<<minute<<":"<<"0"<<sec<<endl;
}
if(is_24==1&&from0==0)
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
if(is_24==0&&from0==1)
{
cout<<"0"<<hour%12<<":"<<minute<<":"<<sec<<" pm"<<endl;
}
else if(hour<12&&hour>=10)
cout<<hour%12<<":"<<minute<<":"<<sec<<" am"<<endl;
else if(hour<10)
cout<<"0"<<hour<<":"<<minute<<":"<<sec<<" am"<<endl;
}
void Time::add_seconds(int s)
{
sec+=s;
while(sec>60)
{
sec-=60;
++minute;
}
while(minute>60)
{
minute-=60;
++hour;
}
while(hour>24)
{
hour-=24;
}
}
void Time::add_minutes(int m)
{
minute+=m;
while(minute>60)
{
minute-=60;
++hour;
}
while(hour>24)
{
hour-=24;
}
}
void Time::add_hours(int h)
{
hour+=h;
while(hour>24)
{
hour-=24;
}
}
void Time::change24()
{
if(is_24=1)
{
is_24=0;
}
else
{
is_24=1;
}
}
void Time::changefrom0()
{
if(from0=1)
{
from0=0;
}
else
{
from0=1;
}
}
bool Time::is_24=1;
bool Time::from0=1;
运行结果: