什么是横向指针转换

What is a transverse pointer cast?

本文关键字:转换 指针 横向 什么      更新时间:2023-10-16

我在Horstmann的Core Java,Volume 1中遇到了这个问题:

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

Core Java Volume I: Fundamentals [Horstmann, Cay S. 2016 Prentice Hall 10th ed. §6.1.3 p. 297]

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

我以前从未见过这个术语,但我认为这是交叉投射的另一个名称,当您需要投射"横跨"(而不是"向上"或"向下")继承图时。采取以下情况:

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

现在假设我们只有静态类型Base1和动态类型Derivedb1,并且我们想要到达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);