这是我的测试示例:
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/