什么是横向指针投射?

时间:2017-01-23 11:49:56

标签: c++ pointers multiple-inheritance

我在Horstmann的核心Java第1卷中遇到过这个问题:

  

C ++有多重继承和随之而来的所有复合,例如虚拟基类,支配规则和横向指针转换......

核心Java第一卷:基础知识[Horstmann,Cay S. 2016 Prentice Hall第10版。 §6.1.3p。 297]

现在,我熟悉其他两个,但什么是横向指针投射?它是将指向基类的指针作为派生类转换的术​​语吗?

1 个答案:

答案 0 :(得分:2)

我之前从未见过这个词,但我认为这是交叉投射的另一个名称,当你需要投射"跨越" (而不是" up"或" down")一个继承图。请考虑以下情况:

// V-shaped inheritance graph

// [ Base1 ]   [ Base2 ]
//      \         /
//       \       /
//      [ Derived ]

struct Base1 { };
struct Base2 { };
struct Derived : Base1, Base2 { };

// ...

// Take an object of derived type
Derived d;

// Upwards conversion, we get its Base1 subobject
Base1 *b1 = &d;

现在假设我们只有b1,静态类型Base1和动态类型Derived,我们想要到达Base2子对象,即转换跨越 V的分支机构。

问题是,我们丢失了*b1实际上是Derived的子对象的信息。它可以是任何其他类的子对象,也可以是对象本身的对象。我们必须使用以下两种工具之一:

// If we know by other means that b1 is for sure a Derived,
// walk the graph explicitly through Derived
Base2 *b2 = /* implicit upwards conversion */ static_cast<Derived*>(b1);

// If Base1 is polymorphic (i.e. has at least one virtual function)
// Let RTTI do the job and check for errors. Slower but safer.
Base2 *b2 = dynamic_cast<Base2 *>(b1);