什么是横向指针转换
What is a transverse pointer cast?
我在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
和动态类型Derived
的b1
,并且我们想要到达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++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- Delphi中的类型转换指针添加
- C++分段错误(核心转储)错误 - 强制转换指针/将函数值返回到线程
- 以C++和运算符优先级键入指向数组成员的强制转换指针
- C++动态强制转换指针的内存清理
- 转换指针和引用的好处
- 在c++中转换指针