我偶然发现了以下问题:我有两个包 A 和 B 各自工作正常。每个都有自己的接口(interface)和自己的实现。现在我制作了一个包C,将A的适配器与B的具体实现相结合。C实际上仅实现了A的接口(interface),并且目前仅在内部继承和使用B的接口(interface)。大多数时候,只需要从容器访问接口(interface) A 就足够了,但现在我也需要可以访问接口(interface) 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 的所有实现细节?
最佳答案
显而易见的解决方案是创建一个组合界面:
class IAB : public virtual IA, public virtual IB
{
};
,让您的 AB1
和 AB2
从中派生(除了它们的
当前推导),并将 IAB*
保留在 vector 中。
这意味着 B1
和 B2
也必须虚拟地派生自
IB
;考虑到事情的发展方向,A
应该
也可能实际上源自IA
。
有强有力的论据表明接口(interface)的继承 应该始终是虚拟的。不用走那么远:如果一个类是 设计为源自,并且它有基础,这些基础 应该是虚拟的(并且可以说,如果一个类的设计不是为了 源自,但你不应该源自它)。就你而言, 你正在使用经典的 mixin 技术,一般来说, 最简单的解决方案是混合中的所有继承 虚拟。
关于c++ - 两个接口(interface)、多重继承合并到一个容器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16186380/