派生类可以做成单例模式么?解决方法
派生类可以做成单例模式么?
如题,他的父类的构造函数如何处理呢?
public: static 我的类* getInstance() {
if( _uniqueInstance == 0 ) {
_uniqueInstance = new 我的类(); //这里报错
}
return _uniqueInstance;
}
我这里报错:object of abstract class type "我的类" is not allowed
------解决方案--------------------
试试用template
------解决方案--------------------
理论上子类跟父类应该是同质的,子类有这样的需求,父类是否应该也有这样的需求?
研究事物是需要应用的时候更科学。
如题,他的父类的构造函数如何处理呢?
public: static 我的类* getInstance() {
if( _uniqueInstance == 0 ) {
_uniqueInstance = new 我的类(); //这里报错
}
return _uniqueInstance;
}
我这里报错:object of abstract class type "我的类" is not allowed
------解决方案--------------------
template<typename T>
class CSingleton
{
public:
static T& Instance()
{
static T me;
return me;
}
};
class MyClass: public CSingleton<MyClass>
{
public:
MyClass(){};
~MyClass(){};
void Print() { printf("testing %d\n",val); }
int val;
};
int main(void)
{
MyClass::Instance().val=7;
MyClass::Instance().Print();
return 0;
}
试试用template
------解决方案--------------------
理论上子类跟父类应该是同质的,子类有这样的需求,父类是否应该也有这样的需求?
研究事物是需要应用的时候更科学。