c++ - 如何使用 reinterpret_cast 转换为 C++ 中的派生类指针

标签 c++ reinterpret-cast

这是我的测试示例:

struct base {
    virtual ~base(){}
    int x;
};

struct derived: public virtual base {
    base * clone() {
        return new derived;
    }
    derived(): s("a") {}
    std::string s;
};

int main () {
    derived d;
    base * b = d.clone();
    derived * t = reinterpret_cast<derived*>(b);
    std::cout << t->s << std::endl;
    return 0;
}

它在我打印 s 的那一行崩溃了。由于“b”是指向派生类的指针,因此 reinterpret_cast 应该可以正常工作。我想知道为什么它会崩溃。同时,如果我用 dynamic_cast 替换 reinterpret_cast,那么它就可以工作。

最佳答案

即使 b此处动态类型为derived , 你必须使用 dynamic_cast .这就是dynamic_cast用于在运行时将基类的指针动态转换为派生类。

reinterpret_cast采用原始指针并将其视为派生类型。但是,由于 virtual继承,必须对指向正确方法分派(dispatch)表的指针进行轻微调整,这正是 dynamic_cast会做的。

关于c++ - 如何使用 reinterpret_cast 转换为 C++ 中的派生类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7409565/

相关文章:

c++ - 获取所有 FPU 寄存器的值,甚至是 "empty"的寄存器

c++ - Visual Studio 将新文件放入错误目录

c++ - 使用 C++ 样式转换从 Void* 转换为 TYPE*​​ : static_cast or reinterpret_cast

C++ 将结构转换为 std::vector<char> 内存对齐

c++ - 我怎样才能摆脱这个 reinterpret_cast,或者这种用法可以吗?

c++ - 如何在不设置最大化的情况下使尺寸最大化?

c++ - 虚拟析构函数 - 内存泄漏

c++ - C++中多继承中使用的reinterpret_cast

c++ - nlohmann JSON,改变一个键的值