我有一个抽象类:
class A
{
public:
bool loaded_;
virtual int load() = 0;
}
还有几个派生类:
class B:public A
{
public:
int load();
static B& instance();
}
class C:public A
{
public:
int load();
static C& instance();
}
事实是::instance() 方法中的代码对于每个类都是相同的:
static B& B::instance()
{
static B instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
static C& C::instance()
{
static C instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
我想分解这个::instance 方法,但是鉴于它使用虚方法::load,我不能在类 A 中定义它。 从理论上讲,我知道这很奇怪,因为类 A 应该有 0 个实例,而 B、C 应该有 1 个实例,但是应该分解这段代码也是有道理的。
你会如何解决这个问题?
最佳答案
您可以使 instance()
成为一个免费的函数模板:
template<class T>
T& instance()
{
static T instance_;
if (!instance_.loaded_)
{
instance_.load();
instance_.loaded_=true;
}
return instance_;
}
然后你可以像这样使用它:
instance<B>().do_stuff()
关于c++ - 抽象类和静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780265/