为什么不能将对象存储为基本虚拟类?
请考虑以下示例:如果Derived
继承了Base
#include <iostream>
#include <memory>
class Base
{
public:
virtual ~Base() = default;
int baseInt = 42;
};
class Derived : public /* virtual */ Base // <<< Uncomment the virtual to get a segfault
{
public:
int derivedInt = 84;
};
int main()
{
Base *base_ptr = new Derived();
Derived *derived_ptr = reinterpret_cast<Derived *>(base_ptr);
std::cout << " baseInt is " << derived_ptr->baseInt
<< ", derivedInt is " << derived_ptr->derivedInt << std::endl; // segv on this line
}
答案 0 :(得分:2)
您使用的reinterpret_cast
仅使用Base
指针,就好像它是Derived
指针。
相反,这是应使用dynamic_cast
的少数情况之一。
the documentation for dynamic_cast
中的示例显示了这种沮丧。