【问题标题】:Initialize static member of class which is itself a class in subclass初始化类的静态成员,该成员本身就是子类中的一个类
【发布时间】:2021-10-05 21:22:56
【问题描述】:

我有两个类,其中一个是另一个的子类。这些类被布置为单例。因此基类包含一个静态成员,该成员设置为该类的唯一实例,并且可以由 getter 函数引用(这里不相关,所以我省略了它)。我现在想在全局上下文中创建子类并将实例保存到静态成员变量中。这基本上就是我所拥有的:

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

但我收到以下错误:

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

这是什么原因?

【问题讨论】:

  • 该成员的类型为LightBase,而不是NormalLight1_0
  • 啊,所以我想如果我想实例化子类它必须是NormalLight1_0 NormalLight1_0::instance_()?
  • 不,我的意思是LightBase 的成员被声明为static LightBase instance_;,它不是NormalLight1_0。匹配的定义是LightBase LightBase::instance_();。我知道这不是你想要的,我只是想指出已经关闭了 decalration,而修复定义是次要的
  • @463035818_is_not_a_number 啊,你看我想在这里使用多态性。所以我应该能够实例化依赖于一些预处理器宏的子类,但在我的instance_ definition 中保持通用。我编辑了这个问题。那么这是否可行?
  • "一些预处理器宏" ?一点都不。我会试着写一个答案...

标签: c++ inheritance static initialization global


【解决方案1】:

您需要指针或引用来实现多态性。 LightBase 成员只能存储 LightBase 而不是其子类之一。因此,问题并不是真正的定义,而是您的声明已经失效。在任何情况下,定义都必须与声明相匹配。

您可以使用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>();

【讨论】:

    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2023-03-18
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多