I use pseudo-interfaces in C ++, i.e. pure abstract classes. Suppose I have three interfaces: IFoo, IBar, and IQuux. I also have a Fred class that implements all three of them:
interface IFoo
{
void foo (void);
}
interface IBar
{
void bar (void);
}
interface IQuux
{
void quux (void);
}
class Fred : implements IFoo, IBar, IQuux
{
}
I want to declare a method that accepts any object that implements IFoo and IBar - for example, Fred will work. The only way to do this, I can imagine, is to define a third IFooAndBar interface that implements both, and redeclare Fred:
interface IFooAndBar : extends IFoo, IBar
{
}
class Fred : implements IFooAndBar, IQuux
{
}
Now I can declare my method as getting IFooAndBar *. So far so good.
However, what happens if I also need another method that accepts IBar and IQuux? I tried to declare a new IBarAndQuux interface and declare Fred as inheriting both:
class IFooAndBar : IFoo, IBar
{
};
class IBarAndQuux : IBar, IQuux
{
};
class Fred : IFooAndBar, IBarAndQuux
{
};
, Fred IFooAndBar ; , Fred:: bar(), gcc :
error: request for member ‘bar’ is ambiguous
error: candidates are: void IBar::bar()
error: void IBar::bar()
.
, Fred , :
class Fred : public IFoo, public IBar, public IBaz
{
};
void doTest (IBarAndBaz* pObj)
{
pObj->bar();
pObj->baz();
}
Fred IBarAndBaz *, , :
error: cannot convert ‘Fred*’ to ‘IBarAndBaz*’ for argument ‘1’ to ‘void doTest(IBarAndBaz*)’
dynamic_cast < > ( )
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 (), , .