下面的代码有问题吗?我对 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/