我在C++中使用伪接口,即纯抽象类。假设我有三个接口,IFoo,IBar和IQuux。我也有一个Fred类实现所有他们三个:C++编译时接口实现检查
interface IFoo
{
void foo (void);
}
interface IBar
{
void bar (void);
}
interface IQuux
{
void quux (void);
}
class Fred : implements IFoo, IBar, IQuux
{
}
我想声明的是接受实现的IFoo和伊巴尔任何对象的方法 - 一弗雷德会的工作,例如。唯一的编译时间的方式来做到这一点,我能想象是定义一个实现这两个第三接口IFooAndBar,并再次声明弗雷德:
interface IFooAndBar : extends IFoo, IBar
{
}
class Fred : implements IFooAndBar, IQuux
{
}
现在我可以宣布我的方法接收IFooAndBar *。到现在为止还挺好。
但是,会发生什么,如果我也想接受伊巴尔和IQuux不同的方法?我试图宣布一个新的接口IBarAndQuux并宣布弗雷德继承两个:
class IFooAndBar : IFoo, IBar
{
};
class IBarAndQuux : IBar, IQuux
{
};
class Fred : IFooAndBar, IBarAndQuux
{
};
这工作当我通过弗雷德作为IFooAndBar的方法;然而,当我尝试叫弗雷德:: bar()的直接,GCC抱怨:
error: request for member ‘bar’ is ambiguous
error: candidates are: void IBar::bar()
error: void IBar::bar()
,这使得该解决方案或多或少没用。
我的下一个尝试是宣布弗雷德从三个单独的接口继承,并且使得该方法接受混合接口作为参数之一:
class Fred : public IFoo, public IBar, public IBaz
{
};
void doTest (IBarAndBaz* pObj)
{
pObj->bar();
pObj->baz();
}
当我试图通过弗雷德作为IBarAndBaz *参数,我得到一个错误,如预期:
error: cannot convert ‘Fred*’ to ‘IBarAndBaz*’ for argument ‘1’ to ‘void doTest(IBarAndBaz*)’
的dynamic_cast <>也p roduces一个错误(我不明白)
error: cannot dynamic_cast ‘pFred’ (of type ‘class Fred*’) to type ‘class IBarAndBaz*’ (source type is not polymorphic)
强制投不工作,但是:
doTest((IBarAndBaz*)pFred);
但我不知道如何安全和便携这是(我开发的Linux, Mac和Windows)以及它是否适用于真实世界的情况。
最后,我知道我的方法可以接受的指针接口之一和dynamic_cast的其他(一个或多个)执行在运行时正确的参数的类型,但我更喜欢一个编译时间的解决方案。
这不安全,它是可移植的。事实上,它在C++中是未定义的。 – 2010-01-18 17:09:46