1. 程式人生 > >用C++設計封裝一個帶鬧鐘的類

用C++設計封裝一個帶鬧鐘的類

include

#include <iostream>
#include <conio.h>
#include <windows.h> 
#include <time.h>
using namespace std;

class Time{     //stantment  class 
    public:
        Time(){     //Define the member constructor
            hour=0;
            min=0;
            sec=0;
            cout
<< "Time"<<endl; } ~Time(){ //desctructor cout<<"~time"<<endl; } void get_time(); // member function declaration void show_time(); void sleep(unsigned long sec); void set_alarm(); void show_alarm(); private
: //private data int year; int month; int day; char week[4]; int hour; int min; int sec; int hour_alarm; int min_alarm; }; void Time::get_time(){ struct tm *t; time_t timer; time(&timer); t=localtime(&timer); switch
(t->tm_wday) { case 1: strcpy(week,"Mon"); break; case 2: strcpy(week,"Tue"); break; case 3: strcpy(week,"Wed"); break; case 4: strcpy(week,"Thu"); break; case 5: strcpy(week,"Fri"); break; case 6: strcpy(week,"Sat"); break; default: strcpy(week,"Sun"); } // week[3]="/0"; year = t->tm_year+1900; month= t->tm_mon+1; day = t->tm_mday; hour = t->tm_hour; min = t->tm_min; sec = t->tm_sec; } void Time::show_time(){ cout<<" *******************************************\n "<<endl; cout<<"YEAR MONTH DAY TIME WEEK "<<endl; cout<<year<<" "<<month<<" "<<day<<" " <<hour<<":"<<min<<":"<<sec<<" "<<week<<"\n"<<endl; cout<<" ******************************************* "<<endl; } void Time::sleep(unsigned long sec) { Sleep(sec); } void Time::set_alarm(){ cout<<"please input alarm hour_time :"<<endl; cin>>hour_alarm; cout<<"please input alarm min_time :"<<endl; cin>>min_alarm; } void Time::show_alarm(){ if(hour_alarm==hour) if(min_alarm==min) cout<<"\n\n\n\nTime is up !"<<endl; //Stop one minutes } int main() { Time t1; t1.set_alarm(); while(!kbhit()) { t1.get_time(); t1.show_time(); t1.show_alarm(); cout<<"\n\n\nPress 'enter' to end"<<endl; t1.sleep(1000); system("cls"); } return 0; } //constructor 是在 建立物件時被就被呼叫了的 //destructor 是在程式結束時被呼叫的

`