将对象作为虚拟类的基础存储

问题描述 投票:1回答:1

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

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

为什么一个人不能将对象存储为基本虚拟类?考虑下面的示例:如果Derived继承自Base #include #include ...

c++ virtual-inheritance
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.