用C++设计一个不能被继承的类
生活随笔
收集整理的這篇文章主要介紹了
用C++设计一个不能被继承的类
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
????? 在C#中定義了關(guān)鍵字sealed,被sealed修飾的類不能被繼承。在Java中同樣也有關(guān)鍵字final表示一個(gè)類型不能被繼承。在C++中沒有類似于sealed和final的關(guān)鍵字,所以我們只有自己來實(shí)現(xiàn)。
????? 很多人都能夠想到,類的構(gòu)造函數(shù)和析構(gòu)函數(shù)是關(guān)鍵。因?yàn)樽宇惖臉?gòu)造函數(shù)會(huì)自動(dòng)調(diào)用父類的構(gòu)造函數(shù)。子類的析構(gòu)函數(shù)也會(huì)自動(dòng)調(diào)用父類的析構(gòu)函數(shù)。所以要想使一個(gè)類不能被繼承,只有把它的構(gòu)造函數(shù)和析構(gòu)函數(shù)都定義為私有函數(shù)或保護(hù)函數(shù),那么當(dāng)一個(gè)類試圖從這個(gè)類繼承的時(shí)候,必然會(huì)先調(diào)用構(gòu)造函數(shù)而產(chǎn)生編譯錯(cuò)誤,從而導(dǎo)致繼承失敗。
????? 這個(gè)不能被繼承類的構(gòu)造函數(shù)和析構(gòu)函數(shù)都是私有函數(shù),那么怎樣才能得到該類的實(shí)例呢? 這倒不難,可以通過定義公有的靜態(tài)函數(shù)來創(chuàng)建和釋放類的實(shí)例,實(shí)現(xiàn)該類不能被繼承但能被實(shí)例化的功能。
????? 基于這個(gè)思路,我們可以寫出如下代碼:
#include<iostream> using namespace std;class SealedClass { private: // 私有成員SealedClass() { }; // 構(gòu)造函數(shù)~SealedClass() { }; // 析構(gòu)函數(shù) public:int m_number;static SealedClass* GetInstance(int number) // 用于構(gòu)造的函數(shù){SealedClass * pInstance = new SealedClass();pInstance->m_number = number;return pInstance;}static void DeleteInstance(SealedClass* pInstance) // 用于析構(gòu)的函數(shù){delete pInstance;pInstance = 0;} };int main(void) {SealedClass * p = SealedClass::GetInstance(9);cout<<"m_number is : "<<p->m_number<<endl;SealedClass::DeleteInstance(p);cout<<"m_number is : "<<p->m_number<<endl;return 0; } 輸出結(jié)果如下:
????? 很多人都能夠想到,類的構(gòu)造函數(shù)和析構(gòu)函數(shù)是關(guān)鍵。因?yàn)樽宇惖臉?gòu)造函數(shù)會(huì)自動(dòng)調(diào)用父類的構(gòu)造函數(shù)。子類的析構(gòu)函數(shù)也會(huì)自動(dòng)調(diào)用父類的析構(gòu)函數(shù)。所以要想使一個(gè)類不能被繼承,只有把它的構(gòu)造函數(shù)和析構(gòu)函數(shù)都定義為私有函數(shù)或保護(hù)函數(shù),那么當(dāng)一個(gè)類試圖從這個(gè)類繼承的時(shí)候,必然會(huì)先調(diào)用構(gòu)造函數(shù)而產(chǎn)生編譯錯(cuò)誤,從而導(dǎo)致繼承失敗。
????? 這個(gè)不能被繼承類的構(gòu)造函數(shù)和析構(gòu)函數(shù)都是私有函數(shù),那么怎樣才能得到該類的實(shí)例呢? 這倒不難,可以通過定義公有的靜態(tài)函數(shù)來創(chuàng)建和釋放類的實(shí)例,實(shí)現(xiàn)該類不能被繼承但能被實(shí)例化的功能。
????? 基于這個(gè)思路,我們可以寫出如下代碼:
#include<iostream> using namespace std;class SealedClass { private: // 私有成員SealedClass() { }; // 構(gòu)造函數(shù)~SealedClass() { }; // 析構(gòu)函數(shù) public:int m_number;static SealedClass* GetInstance(int number) // 用于構(gòu)造的函數(shù){SealedClass * pInstance = new SealedClass();pInstance->m_number = number;return pInstance;}static void DeleteInstance(SealedClass* pInstance) // 用于析構(gòu)的函數(shù){delete pInstance;pInstance = 0;} };int main(void) {SealedClass * p = SealedClass::GetInstance(9);cout<<"m_number is : "<<p->m_number<<endl;SealedClass::DeleteInstance(p);cout<<"m_number is : "<<p->m_number<<endl;return 0; } 輸出結(jié)果如下:
總結(jié)
以上是生活随笔為你收集整理的用C++设计一个不能被继承的类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: const_cast的应用
- 下一篇: s3c2440移植MQTT