C++ - 将两个子类的成员放在共同的位置

C++ - Put members in common for two sub classes

本文关键字:成员 位置 子类 两个 C++      更新时间:2023-10-16

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

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中包含的特定于应用程序的东西放在一起?

我已经查看了维基百科上列出的现有结构设计模式,但似乎没有任何 f 这些模式适用于我的问题。

谢谢。

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

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;
}