【问题标题】:C++ - Put members in common for two sub classesC++ - 将两个子类的成员共用
【发布时间】:2016-03-15 10:13:29
【问题描述】:

让一个库包含以下类层次结构:

class LuaChunk
{
};

class LuaExpr : public LuaChunk
{
};

class LuaScript : public LuaChunk
{
};

现在我想通过扩展这两个类在我的应用程序中使用这个库:

class AppLuaExpr : public LuaExpr
{
private:

    Foo * someAppSpecificMemberFoo;
    Bar * someAppSpecificMemberBar;
};

class AppLuaScript : public LuaScript
{
private:

    Foo * someAppSpecificMemberFoo;
    Bar * someAppSpecificMemberBar;
};

这里的问题是,如果我有很多成员,每个成员都有自己的一对 getter/setter,就会产生很多代码重复。

有没有办法不使用多重继承(我想避免)将AppLuaExprAppLuaExpr 中包含的特定于应用程序的内容公用?

我查看了 Wikipedia 上列出的现有结构设计模式,但似乎这些都不适用于我的问题。

谢谢。

【问题讨论】:

  • 使用 composition 怎么样?使用您的公共成员和代码创建一个类,并将其添加为您的具体类的成员?
  • @Louen 感谢您的帮助。是的,这似乎是一种选择。还有其他想法吗?
  • @songyuanyao 不,我不能那样做。正如我所提到的,上面描述的前 3 个类位于一个库中,我无法向其中添加特定于应用程序的内容,否则它不再是一个库。
  • @Virus721 那么可以制作类模板吗? AppLuaExprAppLuaScript 有什么区别?
  • 为什么要避免多重继承?它旨在解决这个问题。

标签: c++ class inheritance


【解决方案1】:

您可以将公共数据表示为它们自己的类,并在构造过程中传递它。这样您就可以使用组合封装所有内容。

class Core { }; 

class Component { 
    int one, two;
public:
    Component(int one, int two) : one(one), two(two)
    {}
};

class Mobious : public Core 
{
    Component c;
public:
    Mobious(Component &c) : Core(), c(c) { }
};

class Widget : public Core
{
    Component c;
public:
    Widget(Component &c) : Core(), c(c)
    {}
};

int main(void)
{
    Widget w(Component{1, 2});
    Mobious m(Component{2, 3});;
    return 0;
}

【讨论】:

  • 感谢您的帮助。我认为合成是我将要使用的。
  • @Virus721 如果存在只初始化一次但在两个类中都使用的依赖项,请考虑使用shared_ptr(智能指针)来表达。这有助于确保资源仅在您的应用程序中初始化和销毁​​一次。
  • @Virus721 作为记录,这使用 composition(使用成员将功能委托给类)以及 控制反转(通过委托-在构造函数中分类)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 2022-12-09
相关资源
最近更新 更多