为什么不能将一个对象存储为基本虚拟类?
请考虑以下示例:如果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
您使用的reinterpret_cast
仅使用Base
指针好像它是Derived
指针