如何使用reinterpret_cast转换为c ++中的派生类指针 [英] how to use reinterpret_cast to cast to a derived class pointer in c++

查看:329
本文介绍了如何使用reinterpret_cast转换为c ++中的派生类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的测试示例:

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,那么它工作。

It crashes at the line where I print s. Since "b" is a pointer to the derived class, reinterpret_cast should just work. I wonder why it crashes. At the same time, if I replace reinterpret_cast with dynamic_cast, then it works.

推荐答案

即使 b 动态是,您必须使用 dynamic_cast 。这是 dynamic_cast 用于在运行时动态地将基类的指针转换为派生类。

Even if b is here dynamically of type derived, you have to use dynamic_cast. This is what dynamic_cast is for, to dynamically convert a pointer of a base class into a derived class at runtime.

reinterpret_cast 获取原始指针并将其视为派生类型。然而,由于 virtual 继承,必须对指针进行微调以指向正确的方法分派表,这正是 dynamic_cast 会做。

reinterpret_cast takes the raw pointer and considers it as being of the derived type. However, because of the virtual inheritance, a slight adjustment must be done to the pointer to point to the correct method dispatch table, and that's precisely what dynamic_cast will do.

这篇关于如何使用reinterpret_cast转换为c ++中的派生类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆