我有一个 GenericRoot 类,它有许多派生类。我只想创建该类的一个实例。我很熟悉我看到的这种方法here :
class genericRoot {
private:
genericRoot() {}
public:
static genericRoot &getInstance ();
};
class Handler : public genericRoot {
}
但是,这会导致每个处理程序(以及从通用根派生的所有其他类)出现两个错误:
"error: within this context"
"error: genericRoot::genericRoot is private"
有没有一种干净的方法来实现这一点?
最佳答案
当然。将Is there a clean way to accomplish this?
genericRoot
的默认构造函数设为 protected
成员函数。
class genericRoot {
protected:
genericRoot() {}
public:
static genericRoot &getInstance ();
};
话虽如此,我想警告您,对基类对象的需求听起来并不正确。这是某处设计缺陷的症状。仔细考虑一下您的需求,并弄清楚是否有任何方法可以在不创建基类实例的情况下满足需求。
关于c++ - 如何创建基类的单个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53510104/