* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:
* 作者:吳瑕
* 完成日期: 2012年 04月
03日
* 版本號:
*對任務及求解方法的描述部分
* 輸入描述:
* 問題描述:含有靜態數據成員和成員函數的Time類:類中所有的對象共有的數據
#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,在和時制之間轉換
static void changefrom0(); //改變靜態成員from0,切換是否前導
private:
static bool is_24; //爲true時,24小時制,如23:23:5;爲flase,小時制,顯示爲11:23:5 pm
static bool from0; //爲true時,前導0,8:23:5顯示爲08:23:05
int hour;
int minute;
int sec;
};
//下面寫出靜態成員的初始化及各成員函數的定義
Time ::Time(int h,int m, int s)//構造函數的定義
{
hour=h;
minute=m;
sec=s;
}
//爲靜態數據成員初始化
bool Time::is_24=true;
bool Time::from0=false;
void Time:: show_time( )
{
//顯示時
int h;//定義一個數暫時儲存改變的hour值,不然後面的hour值會因此而改變
if(is_24==true&&from0==false)
{
cout<<hour<<":";
}
if(is_24==false&&from0==true) //注意此處的條件
{
if(hour>12)
{
h=hour%12;
cout<<"0"<<h<<":";
}
else
{
if(hour>10&&hour<12)
{
cout<<hour<<":";
}
else
{
cout<<"0"<<hour<<":";
}
}
}
if(is_24==true&&from0==true)
{
if(hour<10)
{
cout<<"0"<<hour<<":";
}
else
{
cout<<hour<<":";
}
}
//顯示分
if(from0==false)
{
cout<<minute<<":";
}
if(from0==true)
{
if(minute<10)
{
cout<<"0"<<minute<<":";
}
else
{
cout<<minute<<":";
}
}
//顯示秒
if(from0==false)
{
cout<<sec;
}
if(from0==true)
{
if(sec<10)
{
cout<<"0"<<sec;
}
else
{
cout<<sec;
}
}
//顯示am/pm
if(is_24==false&&hour>12)
{
cout<<"pm"<<endl;
}
if(is_24==false&&hour<12)
{
cout<<"am"<<endl;
}
}
void Time::change24()//此函數的作用就是爲了改變is_24的值
{
is_24=!is_24;
}
void Time::changefrom0()//此函數的作用就是爲了改變from0的值
{
from0=!from0;
}
void Time::add_seconds(int m) //增加m秒
{
sec=sec+m;
if(sec>=60)
{
add_minutes(int(sec/60));
sec=sec-((sec/60)*60);
}
}
void Time::add_minutes(int m) //增加m分
{
minute=minute+m;
if(minute>=60)
{
add_hours(int(minute/60));
minute=minute-((minute/60)*60);
}
}
void Time::add_hours(int m) //增加m小時
{
hour=hour+m;
if(hour>=24)
{
hour=hour-((hour/24)*24);
}
}
int main( )
{
Time t1(23,14,25),t2(8,45,6);
cout<<"24時制, 不前導:"<<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小時後, 切換是否前導:"<<endl;
cout<< "t1是:";
t1.show_time();
cout<<endl;
cout<< "t2是:";
t2.show_time();
cout<<endl;
t1.change24();
cout<<"換一種制式:"<<endl;
cout<<" t1是:";
t1.show_time();
cout<<" t2是:";
t2.show_time();
system("pause");
return 0;
}
運行結果:
上機感言:
1.要實現一個函數的功能要一步一步想好思路,千萬不要腦子一團麻,就如show函數,輸出時間時要一步一步的輸出!
2.靜態成員函數的功能主要就是爲了引用靜態數據成員,因爲靜態成員不屬於任何一個對象,在類外無法直接引用靜態數據成員!
3.在編寫show函數時,寫判斷條件時費了好大勁啊!