/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.* 文件名称:Time
* 作 者: 郭岩岩
* 完成日期:2012 年4月 2日
* 版 本 号: vc.1
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
*程序头部的注释结束
*/
#include<iostream>
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,切换是否前导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;
};
bool Time::is_24=true;
bool Time::from0=false;
void Time::show_time( )
{
//显示时
int h;
if(!is_24&&hour>12)
h=hour%12;
else
h=hour;
if(from0&&h<10)
{
cout<<"0"<<h<<":";
}
else
cout<<h<<":";
//显示分
if(from0&&minute<10)
{
cout<<"0"<<minute<<":";
}
else
cout<<minute<<":";
//显示秒
if(from0&&sec<10)
{
cout<<"0"<<sec;
}
else
cout<<sec;
//显示am/pm
if(!is_24&&hour>12)
{
cout<<"pm";
}
else
if(!is_24&&hour<12)
{
cout<<"am";
}
}
void Time::add_seconds(int n)
{
if(sec+n>=60)
{
sec=(sec+n)%60;
add_minutes(n/60);
}
else
{
sec=sec+n;
}
}
void Time::add_minutes(int n)
{
if(minute+n>=60)
{
minute=(minute+n)%60;
add_hours(n/60);
}
else
{
minute=minute+n;
}
}
void Time::add_hours(int h)
{
hour+=h;
if (hour>23)
hour%=24;
}
void Time::change24()
{
is_24=!is_24;
}
void Time::changefrom0()
{
from0=!from0;
}
int main( )
{
Time t1(23,14,25),t2(8,45,6);
cout<<"24时制, 不前导0:"<<endl;
cout<<"t1是:";
t1.show_time();
cout<<endl;
cout<<"t2是:";
t2.show_time();
cout<<endl;
t1.add_hours(10);
t2.add_hours(10);
Time::changefrom0(); //注意此处调用静态成员
cout<<"10小时后, 切换是否前导0:"<<endl;
cout<<"t1是:";
t1.show_time();
cout<<endl;
cout<<"t2是:";
t2.show_time();
cout<<endl;
Time::change24();
cout<<"换一种制式:"<<endl;
cout<<"t1是:";
t1.show_time();
cout<<endl;
cout<<"t2是:";
t2.show_time();
cout<<endl;
return 0;
}
上级感言:姜还是老的辣!!!我们的成百行的代码被老师写出来才二三十行
经验积累:在给类中的私有成员赋初值时前面要写上类名和作用域符
is_24=true可以写为is_24