C ++ - 为两个子类共用成员 [英] C++ - Put members in common for two sub classes

查看:229
本文介绍了C ++ - 为两个子类共用成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let a library containing the following class hierarchy :

class LuaChunk
{
};

class LuaExpr : public LuaChunk
{
};

class LuaScript : public LuaChunk
{
};



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

Now I would like to use this library in my application by extending these two classes :

class AppLuaExpr : public LuaExpr
{
private:

    Foo * someAppSpecificMemberFoo;
    Bar * someAppSpecificMemberBar;
};

class AppLuaScript : public LuaScript
{
private:

    Foo * someAppSpecificMemberFoo;
    Bar * someAppSpecificMemberBar;
};

这里的问题是,如果我有很多成员,他们每个都有自己的getter / setter,它会产生大量的代码重复。

The problem here is that, if I have many members, each of them having its own pair of getter/setter, it's going to generate a lot of code duplication.

有一种方法,不使用多重继承(我想避免)应用程序特定的内容包含在 AppLuaExpr AppLuaExpr

Is there a way, that does not use multiple inheritance (which I want to avoid) to put in common the application-specific stuff contained in both AppLuaExpr and AppLuaExpr ?

我已经看过在维基百科上列出的现有结构设计模式,但它似乎并没有任何适应我的问题。

I've taken a look on the existing structural design patterns listed on Wikipedia, but it doesn't seem like any f these is adapted to my issue.

谢谢。

推荐答案

您可以将公共数据表示为自己的类,并在构建过程中传递。这样,你可以使用组合封装所有的东西。

You could express the common data as their own class and pass that during construction. That way you can encapsulate everything using composition.

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

这篇关于C ++ - 为两个子类共用成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆