C++ Clock類模擬實現(xiàn)鬧鐘運行
本文實例為大家分享了C++ Clock類模擬鬧鐘運行的具體代碼,供大家參考,具體內(nèi)容如下
定義一個時鐘類Clock,設(shè)計成員函數(shù)SetAlarm(int hour,int minute,int second)設(shè)置響鈴時間時間;用run()成員函數(shù)模擬時鐘運行,當(dāng)運行到響鈴時間時提示響鈴。
當(dāng)前時間設(shè)置為2時8分58秒,鬧鈴時間設(shè)置為3時40分5秒,時鐘運行時顯示每一秒的時間。


代碼如下:
#include<iostream>
using namespace std;
class Clock{
private:?
?? ?int Hour,Minute,Second,hour,minute,second;
public:
?? ?Clock(int Hour=0,int Minute=0,int Second=0){ ? //構(gòu)造函數(shù)
?? ??? ?this->Hour=Hour,this->Minute=Minute,this->Second=Second;
?? ?}
?? ?~Clock(){} ?//析構(gòu)函數(shù)
?? ?void SetClock(){ ? ?//設(shè)置現(xiàn)在時間(手動輸入)
?? ??? ?cout<<"請輸入一個時間:"<<endl;
?? ??? ?cin>>Hour>>Minute>>Second;
?? ?}
?? ?void SetAlarm(int hour,int minute,int second){ ?//設(shè)置鬧鈴時間(主函數(shù))
?? ??? ?this->hour=hour,this->minute=minute,this->second=second;
?? ?}
?? ?void run(){?? ?
?? ??? ?for(;(Hour!=hour)||(Minute!=minute)||(Second!=second);Second++){
?? ??? ??? ?if(Second==59){ ? ?//秒的進(jìn)位
?? ??? ??? ??? ?Second=0;
?? ??? ??? ??? ?Minute++;
?? ??? ??? ??? ?if(Minute==59){ ?//分的進(jìn)位
?? ??? ??? ??? ??? ?Minute=0;
?? ??? ??? ??? ??? ?Hour++;
?? ??? ??? ??? ??? ?if(Hour==24){ ?//時的循環(huán)
?? ??? ??? ??? ??? ??? ?Hour=0;
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ??? ?cout<<Hour<<"時"<<Minute<<"分"<<Second<<"秒"<<endl; ?//輸出每一秒的時間
?? ??? ?}
?? ?cout<<"Dlinglinglingling~Dlinglinglingling~ ?時間到"<<Hour<<"時"<<Minute<<"分"<<Second<<"秒"<<endl; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //響鈴提示設(shè)置
?? ?}
};
int main(){
?? ?Clock C1;
?? ?C1.SetClock(); ? //設(shè)置現(xiàn)在時間
?? ?C1.SetAlarm(3,40,5); ? //鬧鈴設(shè)置為3時40分5秒
?? ?C1.run(); ? //時鐘運行
?? ?return 0;
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C語言字符函數(shù)isalnum()和iscntrl()詳解

