【发布时间】:2010-05-28 18:27:42
【问题描述】:
我已经构建了几个类(A、B、C...),它们对相同的BaseClass 执行操作。示例:
struct BaseClass {
int method1();
int method2();
int method3();
}
struct A { int methodA(BaseClass& bc) { return bc.method1(); } }
struct B { int methodB(BaseClass& bc) { return bc.method2()+bc.method1(); } }
struct C { int methodC(BaseClass& bc) { return bc.method3()+bc.method2(); } }
但正如您所见,每个类 A、B、C... 仅使用 BaseClass 的可用方法的子集,我想将 BaseClass 拆分为几个块,以便清楚它使用了什么,什么不是。例如,一个解决方案可能是使用多重继承:
// A uses only method1()
struct InterfaceA { virtual int method1() = 0; }
struct A { int methodA(InterfaceA&); }
// B uses method1() and method2()
struct InterfaceB { virtual int method1() = 0; virtual int method2() = 0; }
struct B { int methodB(InterfaceB&); }
// C uses method2() and method3()
struct InterfaceC { virtual int method2() = 0; virtual int method3() = 0; }
struct C { int methodC(InterfaceC&); }
问题是每次添加新类型的操作,都需要更改BaseClass的实现。例如:
// D uses method1() and method3()
struct InterfaceD { virtual int method1() = 0; virtual int method3() = 0; }
struct D { int methodD(InterfaceD&); }
struct BaseClass : public InterfaceA, public InterfaceB, public InterfaceC
// here I need to modify the existing code to add class D
{ ... }
你知道我可以做到这一点的干净方法吗?
感谢您的帮助
编辑:
我忘了提到它也可以用模板来完成。但我也不喜欢这个解决方案,因为所需的接口没有明确出现在代码中。您必须尝试编译代码以验证是否正确实现了所有必需的方法。另外,它需要实例化不同版本的类(每个 BaseClass 类型模板参数一个),这并不总是可行的,也不可取。
【问题讨论】:
标签: c++ interface multiple-inheritance