简体   繁体   English

class B 派生自抽象基础 class A,我如何在 ZA2F2ED4F8EBC2CBB4C21A2DZ A 中使用 singleton

[英]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.

相关问题 当A(派生类)“是”B(基类)时,我们使用继承。 A“可以”B或C时我们该怎么办? - We use inheritance when A (derived class) “is a” B (base class). What do we do when A “can be” B or C? C++ Expand class Base with class Derived that contains a function returning a * b from base class - C++ Expand class Base with class Derived that contains a function returning a * b from base class 如何测试B类是否来自A类? - How to test whether class B is derived from class A? 如何使用基础 class singleton 获取派生 class 的实例? - How can I get an instance of my derived class using base class singleton? 从模板类Base派生类A, <A>以便Base</a> <A>可以使用A :: B?</a> - Derive class A from a template class Base<A> so that Base<A> can use A::B? 在期望它是派生类的基础上使用abstract? - Use abstract within base expecting it to be a derived class? 如何调用基类的虚拟函数定义,该基类在C ++中的抽象基类和派生类中均具有定义? - How can I call virtual function definition of base class that have definitions in both abstract base class and derived class in C++? 从派生的 class 调用具有抽象基 class 的 class --安全 - Calling a class with an abstract base class from a derived class --safely 抽象基类或派生类中的类变量? - Class variable in abstract base class or derived class? 作为抽象类的基类的派生类 - derived class of a base class functioning as an abstract class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM