I have several Abstract Base Classes which act like interfaces as known from Java or C#, let's say these are A, B and C.
Now I have some concrete classes, each implementing a subset of the interfaces:
class Concrete1: public A, public B
class Concrete2: public A, public C
class Concrete3: public A, public C
At some point I'd like to have a method which requires its argument to implement A and C (so it should be possible to pass Concrete2 und Concrete3).
I could do
class AC: public A, public C
cl开发者_如何学Pythonass Concrete1: public A, public B
class Concrete2: public AC
class Concrete3: public AC
and accept a pointer to AC but I don't like this approach, because it might end at something like
class AC: public A, public C
class AB: public A, public B
class ABC: public A, public B, public C
class Concrete1: public AB
class Concrete2: public AC
class Concrete3: public AC
class Concrete4: public AC, public AB, public ABC
Is there any good alternative?
Thanks a lot!
first of all, if these are public abstract base classes and you expect to able to use them as interface types, they need to be virtual -- otherwise you will get duplicate bases and ambiguity problems.
That said, if you need to be able to accept something that is both an 'A' and a 'C' then there really is an 'AC' abstract base class, so you should just declare it as such.
No good alternative exist, I think. Because this problem arose from mistakes at initial interface breakdown.
If its large burden, interfaces redesign is the real good alternative.
Or you could overcome with template method, dynamic_cast, blind C style cast. Or make to two methods for each interfaces.
If AB
, AB
, and ABC
are just interfaces and none of them add any new
function to them, then why not write:
class Concrete4: public ABC
instead of
class Concrete4: public AC, public AB, public ABC
Are they not the same thing?
Of course, if the derived interfaces add new functions to it, then they're not same!
Similarly, you can write ABC
in terms of AB
and C
instead of A
, B
and C
:
//class ABC: public A, public B, public C
class ABC: public AB, public C
Note : I'm assuming that A
,B
,C
, AB
,AC
, and ABC
are all interfaces. i.e they all contain pure virtual functions without defining them. And none of them add any new function to itself, besides having functions from base interface(s).
精彩评论