[英]class B derived from an abstract base class A, and how can i use singleton in class B?
below is the demo code:下面是演示代码:
class A {
public:
A(){}
virtual void method()=0;
//....
virtual ~A(){};
}
class B : public A{
static A * ptr;
//....
public:
//....
static A* GetInstance() {
if (ptr == nullptr)
ptr = new B(); // error, currently B is an abstract class, it has not been constructed
return ptr;
}
//.....
}
class B derived from an abstract base class A, and how can i use singleton in class B? class B 派生自抽象基础 class A,我如何在 ZA2F2ED4F8EBC2CBB4C21A2DZ A 中使用 singleton
You have to implement your method1 inside class B. This is not a problem of Singleton.您必须在 class B 中实现您的方法 1。这不是 Singleton 的问题。 The problem is, that you cannot create an instance of an abstract class.问题是,您不能创建抽象 class 的实例。 Your class B is abstract, because not all pure virtual methods are implemented in class B.您的 class B 是抽象的,因为并非所有纯虚拟方法都在 class B 中实现。
Or do the following:或执行以下操作:
class AImplement: public A class A实现:public A
Inside AImplement, you implement your method1, so that AImplement becomes not abstract.在 AImplement 内部,您实现了您的方法 1,因此 AImplement 变得不抽象。
Now, you can create AImplement inside class B.现在,您可以在 class B 中创建 AImplement。
And do not derive B from A.并且不要从 A 导出 B。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.