简体   繁体   English

初始化类的静态成员,它本身就是子类中的一个类

[英]Initialize static member of class which is itself a class in subclass

I have two classes of which one is a subclass of the other.我有两个类,其中一个是另一个的子类。 The classes are layed out as a singleton.这些类被布置为单例。 So the base class contains a static member which is set to the only instance of that class and can be refered to by a getter function (not relevant here, so I left it out).所以基类包含一个静态成员,它被设置为该类的唯一实例,并且可以被一个 getter 函数引用(这里不相关,所以我省略了它)。 I now want to create the subclass in global context and save the instance to the static member variable.我现在想在全局上下文中创建子类并将实例保存到静态成员变量中。 This is essentially what I have:这基本上是我所拥有的:

class LightBase
{
    protected:
        static LightBase instance_;
    // .. stuff
}

class NormalLight0_5 : public LightBase
{
    //.. other stuff
}

class NormalLight1_0 : public LightBase
{
    //.. other stuff
}

#ifdef CONFIG_LIGHT_TYPE_NORMAL0_5
NormalLight0_5 LightBase::instance_();  // <-- my attempt to instantiate a light of type 0.5
#elif
NormalLight1_0 LightBase::instance_();  // <-- my attempt to instantiate a light of type 1.0
#endif

But I get the following error:但我收到以下错误:

error: no declaration matches 'NormalLight1_0 LightBase::instance_()'

What is the cause of this?这是什么原因?

You need pointers or references for polymorphism.您需要多态性的指针或引用。 A LightBase member can only store a LightBase not one of its subclasses. LightBase成员只能存储LightBase而不是其子类之一。 Hence, it is not really the definition that is the problem, but rather your declaration is already off.因此,问题并不是真正的定义,而是您的声明已经关闭。 In any case the definition must match the declaration.在任何情况下,定义都必须与声明相匹配。

You can use a std::unique_ptr :您可以使用std::unique_ptr

#include <memory>

class LightBase {
    protected:
        static std::unique_ptr<LightBase> instance_;
};

class NormalLight1_0 : public LightBase {};

std::unique_ptr<LightBase> LightBase::instance_ = std::make_unique<NormalLight1_0>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM