两个接口,多个继承组合成一个容器?

时间:2013-04-24 07:49:09

标签: c++ containers multiple-inheritance multiple-interface-implem

我偶然发现了以下问题:我有两个套餐A和B适用于每个人。每个都有自己的接口和自己的实现。现在我创建了一个包C,它将A的适配器与B的具体实现结合起来.C实际上只实现了A的接口,现在只在内部继承和使用B接口。大多数时候只能从Container访问接口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的组合,以便可以从一个Container访问两个接口,而A和B的所有实现细节仍然可以继承?

1 个答案:

答案 0 :(得分:2)

显而易见的解决方案是创建一个组合界面:

class IAB : public virtual IA, public virtual IB
{
};

,让您的AB1AB2从中获得(除了他们的 当前推导),并在矢量中保留IAB*

这意味着B1B2也必须来自 IB;鉴于事情似乎正在发展,A应该 可能也来自IA

有一个强有力的论据,即接口的继承 应该永远是虚拟的。没有走那么远:如果是一个班级 设计来源于,它有基础,那些基础 应该是虚拟的(并且可以说,如果一个类不是为了设计的话 从中得出,你不应该从中得出)。在你的情况下, 你正在使用经典的mixin技术,通常是 最简单的解决方案是在mixin中进行所有继承 虚拟

相关问题