* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:
* 作 者: 李超
* 完成日期: 2012 年 4 月 4 日
* 版 本 號: 01.07.01
* 對任務及求解方法的描述部分
* 輸入描述:
* 問題描述: 含有靜態數據成員和成員函數的Time類:類中所有的對象共有的數據
* 程序輸出:
* 程序頭部的註釋結束
*/
頭文件Time.h
#include <iostream>
using namespace std;
class Time
{
public :
Time (int a = 0, int b = 0, int c = 0):hour(a), minute(b), sec(c){}
void show_time ();//輸出合適形式
void add_seconds(int);//增加n秒
void add_minutes(int);//增加n分鐘
void add_hours(int);//增加n小時
static void change24();//改變靜態成員is_24和from0,在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;//賦值爲true
bool Time::from0 = false;//賦值爲false
void Time::show_time ()//輸出
{
int h = hour;
if(!is_24)
if(hour > 12)
h = hour % 12;
if(h < 10)
if(from0)
cout <<0;
cout <<h <<':';
if(minute < 10)
if(from0)
cout <<0;
cout<<minute <<':';
if (sec < 10)
if (from0)
cout <<0;
cout <<sec;
if(!is_24)
if(hour > 12)
{
cout <<"pm";
}
else
cout <<"am";
cout <<endl;
}
void Time::add_seconds(int x)//增加n秒
{
sec = (sec + x) % 60;
minute += (sec + x) / 60;
}
void Time::add_minutes(int x)//增加n分鐘
{
minute = (minute + x) % 60;
hour += (minute + x) / 60;
}
void Time::add_hours(int x)//增加n小時
{
hour = (hour + x) % 24;
}
void Time::change24()//轉換時制
{
if(is_24)
is_24 = false;
else
is_24 = true;
}
void Time::changefrom0()//是否前導
{
if(from0)
from0 = false;
else
from0 = true;
}
主函數Time.cpp
#include "Time.h"
using namespace std;
int main()
{
Time t1(23,14,25),t2(8,45,6);
cout<<"24時制, 不前導0:"<<endl;
cout<<" t1是:";
t1.show_time();
cout<<" t2是:";
t2.show_time();
t1.add_hours(10);
t2.add_hours(10);
Time::changefrom0(); //注意此處調用靜態成員
cout<<"10小時後, 切換是否前導0:"<<endl;
cout<< "t1是:";
t1.show_time();
cout<< "t2是:";
t2.show_time();
t1.change24();
cout<<"換一種制式:"<<endl;
cout<<" t1是:";
t1.show_time();
cout<<" t2是:";
t2.show_time();
system("pause");
return 0;
}
尚不滿意,願大家多予批評