C++: How can I avoid “invalid covariant return type” in inherited classes without casting?

前端 未结 3 1070
情话喂你
情话喂你 2020-12-30 06:55

I have a quite complex class hierarchy in which the classes are cross-like depending on each other: There are two abstract classes A and C containing a method that returns a

3条回答
  •  孤独总比滥情好
    2020-12-30 07:24

    As far as I know, there's no way to do this without explicit casting. The problem is that the definition of class B can't know that D is a subclass of C until it sees a full definition of class D, but the definition of class D can't know that B is a subclass of A until it sees a full definition of class B, and so you have a circular dependency. This can't be resolved with forward-declarations because a forward declaration unfortunately cannot specify an inheritance relationship.

    There's a similar problem with trying to implement a covariant clone() method using templates, which I found can be solved, but the analogous solution still fails here because the circular reference remains impossible to resolve.

提交回复
热议问题