天天看點

運算符重載——電子時鐘中的運算符重載

題目描述

通過本題目的練習可以運算符重載的方法; 設計一個時間類Time,私有資料成員有hour(時)、minute(分)、second(秒); 公有成員函數有:setHour(int)設定資料成員hour的值,非法的輸入預設為12;setMinue(int)設定資料成員minute的值,非法輸入預設為0;setSecond(int)設定資料成員second的值,非法輸入預設為0;setTime(int,int,int)設定時、分、秒三個資料成員的值;三個成員函數int getHour(); int getMinute(); int getSecond();分别用于擷取時間對象的屬性值。 定義兩個構造函數Time(); 和 Time(int,int,int); 定義一個成員函數void displayTime(); 用于顯示時間,注意格式為 hh:mm:ss,位數不夠用0填充; 定義一個時鐘增加1的成員函數 void tick(); 把second的值加1,并注意是否到60; 定義一個成員或友元函數 bool operator= =(….); 判斷兩個時間對象的值是否相等; 定義一個成員或友元函數bool operator>(…..); 判斷第一個時間對象的值是否大于第二個時間對象的值。     在主函數main()中指定開始時間和結束時間,并調用相應成員函數,顯示從開始時間到結束時間之間所有時間對象的值,其格式見示例輸出。

輸入

輸入6個整數,之間用一個空格間隔;分别表示開始時間的時、分、秒和結束時間的時、分、秒的值

輸出

從開始時間到結束時間之間所有時間對象的值;每個值占一行,格式為hh:mm:ss

示例輸入

01 01 01 01 01 10      

示例輸出

01:01:01
01:01:02
01:01:03
01:01:04
01:01:05
01:01:06
01:01:07
01:01:08
01:01:09
01:01:10      

提示

輸入 11 10 12 10 12 56 輸出 The begin time is not earlier than the end time!  

#include <iostream>
#include <iomanip>
using namespace std;
class Time
{
	public:
		Time(){hour=0;minute=0;sec=0;}
		Time(int h,int m,int s);
		void displayTime();
		void tick();
		friend bool operator ==(Time &t1,Time &t2);
		friend bool operator >(Time &t1,Time &t2);
	private:
		int hour;
		int minute;
		int sec;
};
Time::Time(int h,int m,int s)
{
    hour=h>12?12:h;
    minute=m>59?0:m;
    sec=s>59?0:s;
}
void Time::displayTime()
{
	cout <<setw(2) <<setfill('0') <<hour <<":" <<setw(2) <<setfill('0') <<minute <<":" <<setw(2) <<setfill('0') <<sec <<endl;
}
void Time::tick()
{
	if(++sec>=60)
	{
		sec-=60;
		++minute;
	}
	if(minute>=60)
	{
		minute-=60;
		++hour;
	}
}
bool operator ==(Time &t1,Time &t2)
{
	if(t1.hour==t2.hour && t1.minute==t2.minute && t1.sec==t2.sec)
		return true;
	else
		return false;
}
bool operator >(Time &t1,Time &t2)
{
	if((t1.hour>t2.hour) || (t1.hour==t2.hour && t1.minute>t2.minute) || (t1.hour==t2.hour && t1.minute==t2.minute && t1.sec>t2.sec))
		return true;
	else
		return false;
}
int main()
{
	int hour1,hour2,minute1,minute2,sec1,sec2;
	cin >>hour1 >>minute1 >>sec1 >>hour2 >>minute2 >>sec2;
	Time t1(hour1,minute1,sec1),t2(hour2,minute2,sec2);
	if(operator ==(t1,t2))
		t1.displayTime();
	else if(operator >(t1,t2))
		cout <<"The begin time is not earlier than the end time!" <<endl;
	else
	{
		while(!(operator >(t1,t2)))
		{
			t1.displayTime();
			t1.tick();
		}
	}
	return 0;
}
           

繼續閱讀