【发布时间】:2017-02-11 11:26:52
【问题描述】:
我设置了以下类层次结构,并希望调用非单例基对象 OtherBase 的 print() 函数,该函数又从子类之一调用 printSymbol(),在这种情况下SingletonChild。我知道这是一个复杂且看起来有些不必要的层次结构和做事方式,但这是一项任务,我必须以这种方式去做。
我的问题的一个例子如下:
#include <iostream>
using namespace std;
class Object
{
virtual void print() = 0;
};
class SingletonBase : public Object
{
private:
static SingletonBase* theOnlyTrueInstance;
protected:
SingletonBase()
{
if(!theOnlyTrueInstance)
theOnlyTrueInstance = this;
}
virtual ~SingletonBase(){}
public:
static SingletonBase* instance()
{
if (!theOnlyTrueInstance) initInstance();
return theOnlyTrueInstance;
}
void print()
{ cout<<"Singleton"<<endl; }
static void initInstance()
{ new SingletonBase; }
};
SingletonBase* SingletonBase::theOnlyTrueInstance = 0;
class OtherBase : public Object
{
public:
virtual string printSymbol() = 0;
void print()
{ cout<<printSymbol(); }
};
class SingletonChild : public SingletonBase , public OtherBase
{
public:
string printSymbol()
{
return "Test";
}
static void initInstance()
{ new SingletonChild; }
};
int main() {
SingletonChild::initInstance();
OtherBase* test = (OtherBase*) SingletonChild::instance();
test->print();
return 0;
}
如何让实例test 调用一个基类OtherBase 而不是Singleton 基类SingletonBase 的print 函数?
我尝试过test->OtherBase::print(),但没有成功。
【问题讨论】:
-
您只想让您的
test对象调用OtherBase的print方法而不是SingletonBase的方法? -
@MuhammadAhmad 是的,差不多就是这样。
标签: c++ inheritance design-patterns singleton static-variables