将对象存储为基础 VIRTUAL class

Store object as it's base VIRTUAL class

为什么不能存储一个对象,因为它是基本虚拟的 class?

考虑以下示例:如果 Derived 继承 virtuallyBase[=14,则会发生段错误=]

#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
}

您使用的 reinterpret_cast 只是使用 Base 指针 就好像它是一个 Derived 指针.

相反,这是您应该使用 dynamic_cast 的少数情况之一。 the documentation for dynamic_cast中的示例显示了这种沮丧。