/************************************************************************/ #include <iostream.h> #include <WINDOWS.H> /************************************************************************/ /* 定義一個CLOCK類 */ /************************************************************************/ class CLOCK { private: int hour, minute, second; public: CLOCK(); CLOCK(int, int, int); void update(); void display(); }; /************************************************************************/ /* 定義CLOCK函數 */ /************************************************************************/ CLOCK::CLOCK() { hour = minute = second = 0; cout << "\t One object initialalized." << endl; } /************************************************************************/ /* 定義CLOCK重載函數 */ /************************************************************************/ CLOCK::CLOCK(int h, int m, int s) { hour = h; minute = m; second = s; cout << "\t An object initialalized." << endl; } /************************************************************************/ /* */ /************************************************************************/ void CLOCK::update() { second++; if(second == 60) { second = 0; minute ++; } if (minute == 60) { minute = 0; hour++; } if (hour == 24) { hour = 0; } } /************************************************************************/ /* */ /************************************************************************/ void CLOCK::display() { cout << hour << ":" << minute << ":" << second <<endl; } /************************************************************************/ /* main函數 */ /************************************************************************/ void main() { CLOCK MyClock(12, 0, 0); //聲明類名 while(1) { MyClock.display(); MyClock.update(); Sleep(1000); } }
上面的是函數的重載,
下面是函數的隱藏和覆蓋
#include <IOSTREAM.H> int a = 5; int &b = a; /************************************************************************/ /* Base */ /************************************************************************/ class Base { public: virtual void fn(); }; /*Derived類的fn(int)函數隱藏了Base類的fn函數*/ class Derived:public Base { public: /*派生類的函數與基類的函數同名,但參數列表不同 在這種情況下,不管基類的函數聲明是否有virtual 關鍵字,基類的函數都將被隱藏。*/ void fn(int); }; /*Derived2類的fn()函數隱藏了Derived類的fn(int) */ class Derived2:public Derived { public: void fn(); }; class animal { public: void eat() { cout << "animal eat" << endl; } void sleep() { cout << "animal sleep" << endl; } void breathe() { cout << "animal breathe" << endl; } }; class fish:public animal { public: void breathe() { cout << "fish bubble" << endl; } }; void fn(animal *pAn) { pAn->breathe(); } void main() { animal *pAn; fish fh; pAn = &fh; fn(pAn); }