這是怎麼回事: 問題是這樣的 - 爲了讓我的程序跨平臺,我爲操作系統執行的操作完成了一個抽象層。有一個抽象基類,稱爲SystemComponent
這看起來是這樣的:如何將一個抽象類變成一個單例對象?
class SystemComponent{
public:
//some functions related to operations for OS
virtual WindowHandle CreateNewWindow(/*...*/) = 0;
virtual void Show_Message(/*...*/) = 0;
//...
}
這然後通過另一個操作系統特定的類繼承的,比如說爲Windows的WindowsSystemComponent
:
#ifdef _WIN23
class WindowsSystemComponent : SystemComponent{
public:
virtual WindowHandle CreateNewWindow(/*...*/);
virtual void Show_Message(/*...*/);
//...
protected:
//Windows specific things...
}
#endif
這WindowsSystemComponent
然後impliments的OS特定的功能。
在Windows中創建一個系統組件,我這樣做:
WindowsSytemComponent* pWSystemComp = new WindowSystemComponent();
//...
//And the pass a pointer to this to the crossplatform code like this
pFrameWork->SetSystem((SystemComponent*)pWSystemComp);
,其中框架可通過在SystemComponent
指定的OS功能的調用,並傳遞到任何子類需要它的指針。
需要什麼樣的: 我想刪除指針的傳球,使SystemComponent
類和OS特定功能implimentations acsessible到想要使用它們每個對象。要做到這一點的最佳方法是使它成爲一個單身,但whin我嘗試做一些像
virtual static SystemComponent* Instance() { /*...*/ };
的SystemComponent
類,它是抽象的裏面,我得到一個編譯錯誤,說這樣的事情是不允許的。
那麼,我應該怎麼做呢?
相關:http://stackoverflow.com/questions/22998019/template-singleton-base-class-in-shared-object/22998472#22998472 – 2014-10-06 16:35:41