【发布时间】: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