我偶然发现了以下问题:我有两个软件包A和B都可以正常工作。每个都有自己的接口(interface)和自己的实现。现在,我制作了一个包C,将A的适配器与B的具体实现组合在一起。C实际上仅实现A的接口(interface),并且目前仅在内部继承和使用B的接口(interface)。在大多数情况下,足以从容器访问接口(interface)A,但是现在我也需要从B访问方法。这是简单的示例:
//----Package A----
class IA
{virtual void foo() = 0;};
// I cant add simply bar() here, it would make totally no sense here...
class A : public IA
{virtual void foo() {doBasicWork();} };
//----Package B----
class IB
{virtual void bar() = 0;};
class B1 : public IB
{
//Some special implementation
virtual void bar() {}
};
class B2 : public IB
{
//Some special implementation
virtual void bar() {}
};
// + several additional B classes , with each a different implementation of bar()
//---- Mixed Classes
class AB1 : public B1, public A
{
void foo() {A::foo(); B1::bar();}
};
class AB2 : public B2, public A
{
void foo() {A::foo(); B2::bar();}
};
// One Container to rule them all:
std::vector<IA*> aVec;
AB1 obj1;
AB2 obj2;
int main(){
iAvector.push_back(&obj1);
iAvector.push_back(&obj2);
for (std::vector<IA>::iterator it = aVec.begin(); it != aVec.end(); it++)
{
it->for(); // That one is okay, works fine so far, but i want also :
// it->bar(); // This one is not accessible because the interface IA
// doesnt know it.
}
return 0;
}
/* I thought about this solution: to inherit from IAB instead of A for the mixed
classes, but it doesnt compile,
stating "the following virtual functions are pure within AB1: virtual void IB::bar()"
which is inherited through B1 though, and i cant figure out where to add the virtual
inheritence. Example:
class IAB : public A, public IB
{
// virtual void foo () = 0; // I actually dont need them to be declared here again,
// virtual void bar () = 0; // do i?
};
class AB1 : public B1, public IAB
{
void foo() {A::foo(); B1::bar();}
};
*/
问题是,如何实现包A和包B的组合,以便可以从一个容器访问两个接口(interface),同时仍继承A和B的所有实现细节?
最佳答案
显而易见的解决方案是创建一个组合接口(interface):
class IAB : public virtual IA, public virtual IB
{
};
,让您的
AB1
和AB2
衍生自(除了他们的当前导数),并将
IAB*
保留在 vector 中。这意味着
B1
和B2
也必须实际上源自IB
;给定事物似乎前进的方向,A
应该可能实际上也从
IA
派生。有很强的论点表明接口(interface)的继承
应该始终是虚拟的。不用走那么远:如果一个类(class)是
设计为从这些基础衍生并具有这些基础
应该是虚拟的(并且可以说,如果一个类的设计目的不是为了
衍生自,则不应衍生自)。就你而言
您使用的是经典的混合技术,通常,
最简单的解决方案是将mixin中的所有继承
虚拟。
关于c++ - 两个接口(interface),多个继承合并到一个容器中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16186380/