用C++設計一個不能被繼承的類

來源:互聯網
上載者:User

      在C#中定義了關鍵字sealed,被sealed修飾的類不能被繼承。在Java中同樣也有關鍵字final表示一個類型不能被繼承。在C++中沒有類似於sealed和final的關鍵字,所以我們只有自己來實現。
      很多人都能夠想到,類的建構函式和解構函式是關鍵。因為子類的建構函式會自動調用父類的建構函式。子類的解構函式也會自動調用父類的解構函式。所以要想使一個類不能被繼承,只有把它的建構函式和解構函式都定義為私人函數或保護函數,那麼當一個類試圖從這個類繼承的時候,必然會先調用建構函式而產生編譯錯誤,從而導致繼承失敗。
      這個不能被繼承類的建構函式和解構函式都是私人函數,那麼怎樣才能得到該類的執行個體呢? 這倒不難,可以通過定義公有的靜態函數來建立和釋放類的執行個體,實現該類不能被繼承但能被執行個體化的功能。
      基於這個思路,我們可以寫出如下代碼:

#include<iostream>using namespace std;class SealedClass{private:                      // 私人成員SealedClass() {  };       // 建構函式~SealedClass() {  };      // 解構函式public:int m_number;static SealedClass* GetInstance(int number)              // 用於構造的函數{SealedClass * pInstance = new SealedClass();pInstance->m_number = number;return pInstance;}static void DeleteInstance(SealedClass* pInstance)       // 用於析構的函數{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;}

輸出結果如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.