如何解决在父类方法中初始化派生类的静态变量
我正在尝试减少初始化派生类静态成员的 init 函数中的代码重复。就我而言,此函数称为 initTypeInfo
。最初,我的每个子类 ChildA
、ChildB
... ChildN
都有自己的 initTypeInfo
。一旦我决定将 initTypeInfo
移入 Parent
类,因为除了静态成员的命名空间(ChildA::s_typeInfo
与 ChildB::s_typeInfo
...)之外的几乎所有代码都是同样,我开始发现静态成员 s_typeInfo
有问题。此变量是 std::shared_ptr<TypeInfo>
这是我的代码示例:
#include <string>
#include <memory>
#include <iostream>
struct TypeInfo
{
std::string name;
// other members ...
};
class Parent
{
public:
Parent(std::string name)
: m_name(name)
{
}
virtual std::shared_ptr<TypeInfo> getTypeInfo() = 0;
virtual void initTypeInfo()
{
// this function contains lots of common code,trying to avoid code duplication
std::shared_ptr<TypeInfo> typeInfo = getTypeInfo();
// initialize if it hasn't already been initialized
if (typeInfo == nullptr)
{
TypeInfo info {m_name};
// the variable Child<n>::s_typeInfo doesn't point to this allocated data :(
typeInfo = std::make_shared<TypeInfo>(info);
}
}
private:
std::string m_name;
};
class ChildA : public Parent
{
public:
ChildA(std::string name /*other params...*/)
: Parent(name)
{
initTypeInfo();
}
std::shared_ptr<TypeInfo> getTypeInfo()
{
return s_typeInfo;
}
private:
inline static std::shared_ptr<TypeInfo> s_typeInfo = nullptr;
// other members...
};
class ChildB : public Parent
{
public:
ChildB(std::string name /*other params...*/)
: Parent(name)
{
initTypeInfo();
}
std::shared_ptr<TypeInfo> getTypeInfo()
{
return s_typeInfo;
}
private:
inline static std::shared_ptr<TypeInfo> s_typeInfo = nullptr;
// other members...
};
int main()
{
ChildA ca1("childa1");
ChildA ca2("childa2");
ChildB cb1("Childb1");
return 1;
}
所以我的问题是:
- 这是一个糟糕的设计,我在父类中初始化静态成员
- 如何解决此处的代码重复问题?
- 我知道按值返回是从函数返回智能指针的首选方式。但是在这种情况下,我如何让我的成员
Child<n>::s_typeInfo
指向我在Parent::initTypeInfo()
中分配的数据
我在网上关注的链接将我指向 this link,所以我想我可以使用模板来实现这一点,但我不相信这是唯一的方法。
编辑 1:
实际上,TypeInfo
不仅包含一个数据成员。这是一个具有多个数据成员和方法的复杂类。最初我在每个派生类中都有 initTypeInfo
函数,这些函数会初始化每个 s_typeInfo
。然而,事实证明所有这些 initTypeInfo
函数中的逻辑是相同的!唯一的区别是必须初始化每个派生类的特定 s_typeInfo
。所以我想要一种方法来将逻辑转移到 Parent
类中(从而减少重复),但也在父类中初始化静态 s_typeNode
。我想,或者问题可能是,我如何让子类 shared_ptr
指向我在 TypeInfo
中创建的 Parent::initTypeInfo()
?
s_typeInfo
作为静态成员存在的原因是因为我想在某个 Child 的所有实例之间共享该类。因此,在我的主要内容中,例如,如果我启动了 ChildA
的 4 个实例,我需要它们共享一个 ChildA::s_typeInfo
,如果我有 10 个 ChildB
实例,我需要它们共享一个 { {1}}。
编辑 2:
为我想要实现的目标添加最少的代码示例。我期望 ChildB::s_typeInfo
为 1 而不是 *(c.p)
,因为我是通过引用从 nullptr
返回的。
C::get()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。