C++ cannot convert from base A to derived type B via virtual base A

后端 未结 7 1478
不知归路
不知归路 2020-12-04 16:43

I have three classes:

class A {};

class B : virtual public A {};
class C : virtual public A {};

class D: public B, public C {};

Attemptin

7条回答
  •  星月不相逢
    2020-12-04 17:04

    According standard docs,

    Section 5.2.9 - 9, for Static Cast,

    An rvalue of type “pointer to cv1 B,” where B is a class type, can be converted to an rvalue of type “pointer to cv2 D,” where D is a class derived (clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D.

    Hence, it is not possible and you should use dynamic_cast...

提交回复
热议问题