C++ - 将两个子类的成员放在共同的位置
C++ - Put members in common for two sub classes
让一个包含以下类层次结构的库:
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,它将产生大量的代码重复。
有没有一种方法,不使用多重继承(我想避免)将AppLuaExpr
和AppLuaExpr
中包含的特定于应用程序的东西放在一起?
我已经查看了维基百科上列出的现有结构设计模式,但似乎没有任何 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;
}
相关文章:
- 内存中类位置的成员是否取决于类成员在类定义中的位置?
- 处于默认参数位置的 Lambda 无法访问好友成员。这是编译器错误吗?
- POD 结构(相同类型的成员):成员是否位于连续的内存位置?
- 非常量调用 const 成员函数失败,只读位置C++
- 基本指针如何能够在派生的类实例中了解基本成员的内存位置
- 如何在G 代码中找到给定的成员函数或CTOR的所有位置
- 是STD :: Vector,由于其分配运算符移动其成员的位置,因此是一种非常规类型
- C++类成员和内存位置
- 类成员和成员函数的内存位置
- 类定义中定义的成员函数的编译方式是否与C++中其他位置定义的成员函数不同
- 在特定位置分配多态类成员
- 测试静态常量成员的存储位置
- C++ - 将两个子类的成员放在共同的位置
- 初始化静态成员变量值的正确位置
- 易失性关键字在C++中成员函数声明中的位置
- 当使用new()创建数组时,数组的所有成员都位于同一内存位置
- 当从不同位置访问类方法时,类成员的位置会发生变化
- 确定一个位置是否是特定列表的成员
- 类的成员变量在堆中的存储位置
- 存储成员函数的位置