如何返回对象或调用基为单例的派生类的getInstance
You would have to use virtual static method, which is not supported in C++ (It's supported in Delphi, as far as I remember - a curiosity).
You have to decide, whether there's only one instance of both classes or of each class (eg. if you create a Derived instance by GetInstance, should you be able to create Base instance).
There is no way to solve this problem inside these classes, you have to create a class factory. Something like that (I've ommited the singleton implementation to make the idea more clear - obviously you know, how to implement one)
class SingletonFactory
{
template<typename T>
static T * GetInstance()
{
return T.GetInstance();
}
};
class Base
{
friend class SingletonFactory;
private:
static Base * GetInstance()
{
// ...
}
protected:
Base()
{
}
};
class Derived : public Base
{
friend class SingletonFactory;
private:
static Derived * GetInstance()
{
}
protected:
Derived()
: Base()
{
}
};
// (...)
Derived * d = SingletonFactory::GetInstance<Derived>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.