什么是横向指针转换?

What is a transverse pointer cast?

我在 Horstmann 的核心 Java,第 1 卷中遇到了这个:

C++ has multiple inheritance and all the compications that come with it, such as virtual base classes, dominance rules, and transverse pointer casts...

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

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

我以前从未见过这个词,但我认为这是 cross-cast 的另一个名称,当您需要转换 "across" (而不是 "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 的子对象的信息。它可以是任何其他 class 的子对象,也可以是它自己的对象。我们必须使用以下两个工具之一:

// 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);