c++ - 使用reinterpret_cast

标签 c++ inheritance multiple-inheritance reinterpret-cast

下面的代码有问题吗?我对 reinterpret_cast 的使用特别感兴趣。

class Base1
{
public:
    virtual void foo(){}
};

class Base2
{
public:
    virtual void bar(){}
};

class Derived : public Base1, public Base2
{
};

int main()
{
    Base1* instance1 = new Derived();
    instance1->foo();

    Base2* instance2 = reinterpret_cast<Base2*>(instance1);
    instance2->bar();

    return 0;
}

最佳答案

reinterpret_cast 不知道如何处理同级之间的转换(例如,在 vtable 实现中,它不会修复 this 指针),因此它肯定无法工作。请注意,它可能看起来符合您的预期。在这种情况下,您需要使用 dynamic_cast,或者使用 static_cast 进行派生并使用到 base2 的隐式转换。

关于c++ - 使用reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528199/

相关文章:

带有继承的java静态初始化

Python:为什么 MRO 中的最后一个类在其 super 的 __init__ 调用中应该有零参数,否则会出现运行时异常

c++ - Netbeans 忽略文件

c++ - 使用 GDI+ 和 C++ 将 JPEG 编码的屏幕截图保存到缓冲区

c++ - 从双数据类型获取特定整数的方法

java - JPA继承要求子类中的ID

c++ - Cmake 外部资源

c++ - 为什么 C++ 允许将指向基对象的指针转换为派生类的指针

java - 是否可以在 Java 中扩展泛型类参数?

php - 我应该如何避免多个类继承的需要