c++ - 在 C++ 中向上转型和向下转型跳过层次结构?

标签 c++ casting

我已经搜索过这个特定的问题,但找不到它,所以就在这里。跳过中间的类来向上或向下转换好吗?

示例代码-

class Base { }
class Derived : public Base { }
class DerivedOfDerived : public Derived { }
class DerivedOfDOD : public DerivedOfDerived { }

int main()
{
    DerivedOfDOD *dodod = new DerivedOfDOD();
    Base *b = static_cast<Base *>(dodod);
    Derived *d = static_cast<Derived *>(b);
    back_to_b = static_cast<Base *>(d);
    DerivedOfDerived *dod = static_cast<DerivedOfDerived *>(back_to_b);
    delete dodod;
}

这是有效的代码吗?以及对编译器如何管理地址和这种转换的解释将不胜感激。

最佳答案

Is it fine to upcast or downcast by skipping the classes in the middle?

是的。

Is this valid code?

是的。 (如果我们忽略内存泄漏的话)

附言向上转换是隐式的,因此 Base *b = dodod; 就足够了。

关于c++ - 在 C++ 中向上转型和向下转型跳过层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54423130/

相关文章:

c++ - 转换 : #define xxxxxx ((LPCSTR) 4)

ios - 将 Dictionary 转换为 AnyObject 时出现编译器错误?

swift - For-in 循环和类型转换仅适用于匹配类型的对象

c - C中的函数指针问题

c++ - 使用 C 中内存地址的 Julia 读/写结构数据

c++ - Visual Lint 中的每个项目选项?

C++临时变量解释

c++ - Qt/C++ 基于比较的信号调度的优雅方式

c# - c# 'bracketed' 类型转换的运行时等效项是什么

java - getter 和 setter 的 Eclipse 模板变量