麵向對象中的重載、覆蓋和隱藏
1.重載是一個類內部實現相同機理的操作,但是操作的對象不同。主要體現在:
- 方法在同一個類中
- 重載的方法名稱相同
- 參數不同(參數的類型不同,參數的個數不同)
- virtual關鍵字可有可無
#include "stdafx.h" #include<iostream> using namespace std; class father { public: void DoJob(int a); void DoJob(double a); void DoJob(int a, int b); void DoJob(int a, int b, int c); ~ father(); private: }; void father::DoJob(int a) { cout << "one parameter:" << a << endl; } void::father::DoJob(double a) { cout << "one double parameter:" << a << endl; } void father::DoJob(int a, int b) { cout << "two parameter: " << a << " and " << b << endl; } void father::DoJob(int a, int b, int c) { cout << "three parameter:" << a << " and " << b << " and " << c << endl; } father::~ father() { } int _tmain(int argc, _TCHAR* argv[]) { father f; f.DoJob(4); f.DoJob(4.3); f.DoJob(5, 6); f.DoJob(4, 5, 6); return 0; }father類的DoJob方法實現了重載,其中既有參數類型不同的重載,也有參數個數不同的重載。
2.覆蓋,就是麵向對象中的多態,是子類的方法覆蓋了基類的方法,以實現不同的功能,或者對父類的功能進行擴充。主要體現在:
- 派生類函數覆蓋基類函數
- 不同的範圍(分別位於派生類和基類中)
- 函數名稱相同
- 參數相同
- 基類函數必須有virtual關鍵字
#include "stdafx.h" #include<iostream> using namespace std; class father { public: virtual void DoJob(int a); ~ father(); private: }; void father::DoJob(int a) { cout << "one parameter in base class:" << a << endl; } father::~ father() { } class son :public father { public: void DoJob(int a); ~son(); }; void son::DoJob(int a) { cout << "one parameter in son class:" << a << endl; } son::~son() {} int _tmain(int argc, _TCHAR* argv[]) { son s; father *f = &s; f->DoJob(5); return 0; }
上述代碼的運行結果為:
上麵的代碼中子類son中的函數DoJob()對父類father中的函數DoJob()進行了覆蓋。
3.隱藏是派生類的函數屏蔽了與其同名的基類函數。其特點主要體現在:
- 如果派生類的函數與基類的函數同名,但是參數不同。此時,不論有無virtual關鍵字,基類的函數都將被覆蓋。
- 如果派生類的函數與基類的函數同門,並且參數也相同,但是基類函數沒有virtual關鍵字。此時,基類的函數也將被隱蔽。還記得嗎如果此時基類函數如果有virtual,子類函數就覆蓋了父類函數。
#include "stdafx.h" #include<iostream> using namespace std; class father { public: virtual void DoJob(int a); virtual void DoJob(int a, int b); ~ father(); private: }; void father::DoJob(int a) { cout << "one parameter in base class:" << a << endl; } void father::DoJob(int a, int b) { cout << "two parameter in base class:" << a << " and " << b << endl; } father::~ father() { } class son :public father { public: void DoJob(double a); ~son(); }; void son::DoJob(double a) { cout << "one parameter in son class:" << a << endl; } son::~son() {} int _tmain(int argc, _TCHAR* argv[]) { son s; s.DoJob(1); s.DoJob(2, 3); return 0; }
對上麵的代碼進行編譯,會出現錯誤:
error C2660: “son::DoJob”: 函數不接受 2 個參數,這就說明基類father中的DoJob(int a,int b)函數被隱藏了。
最後更新:2017-04-03 12:54:03