将对象存储为基本VIRTUAL类

时间:2019-11-22 12:30:58

标签: c++ virtual-inheritance

为什么不能将对象存储为基本虚拟类?

请考虑以下示例:如果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
}

1 个答案:

答案 0 :(得分:2)

您使用的reinterpret_cast仅使用Base指针,就好像它是Derived指针

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