我有三个班级:
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D: public B, public C {};
尝试从 A* 静态转换到 B* 我收到以下错误:
Attempting a static cast from A* to B* I get the below error:
cannot convert from base A to derived type B via virtual base A
为了理解强制转换系统,您需要深入研究对象模型.
In order to understand the cast system, you need to dive into the object model.
简单层次模型的经典表示是包含:如果 B
派生自 A
那么 B
对象实际上将包含一个 A
子对象以及它自己的属性.
The classic representation of a simple hierarchy model is containment: if B
derives from A
then the B
object will, in fact, contain an A
subobject alongside its own attributes.
使用此模型,向下转换是通过编译时已知的偏移量进行简单的指针操作,这取决于 B
的内存布局.
With this model downcasting is a simple pointer manipulation by an offset known at compilation time, which depends on the memory layout of B
.
这就是 static_cast 的作用:静态转换被称为静态转换,因为转换所需的计算是在编译时完成的,无论是指针算术还是转换 (*).
This is what static_cast does: a static cast is dubbed static because the computation of what is necessary for the cast is done at compile-time, be it pointer arithmetic or conversions (*).
然而,当 virtual
继承开始时,事情往往变得有点困难.主要问题是使用 virtual
继承所有子类共享子对象的相同实例.为了做到这一点,B
将有一个指向 A
的指针,而不是一个 A
本身,而 A
code> 基类对象将在 B
之外实例化.
However, when virtual
inheritance kicks in, things tend to become a bit more difficult. The main issue is that with virtual
inheritance all subclasses share the same instance of the subobject. In order to do that, B
will have a pointer to an A
, instead of an A
proper, and the A
base class object will be instantiated outside of B
.
因此,在编译时不可能推导出必要的指针算法:这取决于对象的运行时类型.
Therefore, it's impossible at compilation time to be able to deduce the necessary pointer arithmetic: it depends on the runtime type of the object.
每当有运行时类型依赖项时,您都需要 RTTI(运行时类型信息),而利用 RTTI 进行强制转换是 dynamic_cast 的工作.
Whenever there is a runtime type dependency, you need RTTI (RunTime Type Information), and making use of RTTI for casts is the job of dynamic_cast.
总结:
static_cast
dynamic_cast
另外两个也是编译时强制转换,但它们非常具体,以至于很容易记住它们的用途……而且它们很臭,所以无论如何最好不要使用它们.
The other two are also compile-time casts, but they are so specific that it's easy to remember what they are for... and they are smelly, so better not use them at all anyway.
(*) 正如@curiousguy 在评论中所指出的,这仅适用于向下转换.static_cast
允许向上转换,而不管是虚拟继承还是简单继承,尽管这样转换也是不必要的.
(*) As noted by @curiousguy in the comments, this only holds for downcasting. A static_cast
allows upcasting regardless of virtual or simple inheritance, though then the cast is also unnecessary.
这篇关于C++ 不能通过虚基 A 从基 A 转换为派生类型 B的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!