gpt4 book ai didi

c++ - 什么是横向指针转换?

转载 作者:行者123 更新时间:2023-11-28 01:54:14 24 4
gpt4 key购买 nike

我在 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]

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

最佳答案

我以前从未见过这个词,但我认为这是 cross-cast 的另一个名称,当你需要“跨越”(而不是“向上”或“向下”)时) 继承图。考虑以下情况:

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

关于c++ - 什么是横向指针转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com