在钻石层次结构中向下转换 [英] Downcast in a diamond hierarchy

查看:191
本文介绍了在钻石层次结构中向下转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 static_cast 无法从虚拟基础向下转换?

Why static_cast cannot downcast from a virtual base ?

struct A {};
struct B : public virtual A {};
struct C : public virtual A {};
struct D : public B, public C {};

int main()
{
  D d;
  A& a = d;
  D* p = static_cast<D*>(&a); //error
}  

g ++ 4.5说:

g++ 4.5 says:

 error: cannot convert from base ‘A’ to derived type ‘D’ via virtual base ‘A’

解决方案是使用 dynamic_cast ?但为什么。什么是理性?

The solution is to use dynamic_cast ? but why. What is the rational ?

- 编辑 -

以下非常好的答案。没有答案详细确切地说明了子对象和vtables如何最终订购。以下文章提供了gcc的一些很好的示例:

http:// www.phpcompiler.org/articles/virtualinheritance.html#Downcasting

-- edit --
Very good answers below. No answers detail exactly how sub objects and vtables end up to be ordered though. The following article gives some good examples for gcc:
http://www.phpcompiler.org/articles/virtualinheritance.html#Downcasting

推荐答案

因为如果对象实际上是类型 E (源自D), A 子对象相对于 D subobject可能与对象实际上 D 不同。

Because if the object was actually of type E (derived from D), the location of A subobject relative to D subobject could be different than if the object is actually D.

考虑而不是从A到C.当你分配C,它必须包含A的实例,它生活在一些特定的偏移量。但是当你分配D时,C子对象指的是B的A的实例,所以它的偏移是不同的。

It actually already happens if you consider instead casting from A to C. When you allocate C, it has to contain instance of A and it lives at some specific offset. But when you allocate D, the C subobject refers to the instance of A that came with B, so it's offset is different.

这篇关于在钻石层次结构中向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆