【发布时间】:2013-07-28 23:35:29
【问题描述】:
所以不可能通过虚拟继承使用static_cast进行向下转换,但是如何进行以下向上转换:
class Base {...};
class Derived : public virtual Base {...};
...
Derived *d = new Derived();
Base *b = static_cast<Base*>(d);
对象的内存布局:
[ derived part | base part ]
我知道向上转换被认为是“安全的”,但是当继承是虚拟的时,编译器如何知道编译时基本子对象的偏移量? static_cast 使用 vtable 吗?
当我们有这样的东西时,这尤其令人困惑(注意它不是虚拟的):
class Third : public Derived {...};
...
Derived *d = new Third(); // non-virtual upcast, no offset will be added
Base *b = static_cast<Base*>(d);
这次我使用了相同的static_cast 行,但是Base 子对象的偏移量不同!
对象的内存布局:
[ derived part | third part | base part ]
那么如何在编译时确定,如果取决于d指向的对象的实际动态类型呢?
【问题讨论】:
-
非常有趣的问题;我希望有更详细的问题
标签: c++ oop virtual-inheritance static-cast