【发布时间】:2014-10-06 16:28:34
【问题描述】:
案件内容:
问题是这样的——为了让我的程序跨平台,我为操作系统执行的操作做了一个抽象层。有一个抽象基类,名为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 然后隐含了操作系统特定的功能。
要在 Windows 中创建系统组件,我这样做:
WindowsSytemComponent* pWSystemComp = new WindowSystemComponent();
//...
//And the pass a pointer to this to the crossplatform code like this
pFrameWork->SetSystem((SystemComponent*)pWSystemComp);
框架调用SystemComponent 中指定的操作系统函数,并将指针传递给任何需要它的子类。
需要什么:
我想删除指针的传递,并使 SystemComponent 类和操作系统特定的函数实现对每个想要使用它们的对象都可访问。最好的方法是让它成为一个单例,但是当我尝试做类似的事情时
virtual static SystemComponent* Instance() { /*...*/ };
在抽象的SystemComponent 类中,我得到一个编译器错误,说这样的事情是不允许的。
那我应该怎么做呢?
【问题讨论】:
标签: c++ inheritance singleton