首页 > 解决方案 > 如果存在虚函数,则无法通过地址减法/加法到达成员变量的地址

问题描述

我们正在与一个团队一起开发一个引擎,一个特定的功能将要求我们通过向类的地址添加值来访问每个成员的内存地址。这对于组件保存-加载系统是必需的,其中组件的每个成员都将被保存,然后如果用户加载场景则重新加载。显然,由于用户也可以创建组件,我们不能只是继续手动设置每个成员的值——因为用户创建的那些我们并不知道。在写这篇文章时,我发现虚拟功能被中断了——最初我不知道为什么我们无法联系到成员。
在以下场景中,我想访问 Component 类的 componentID 变量。

组件.h:

class Component
{
private:
    static int componentID_Count;

protected:
    virtual void Start() {};
    virtual void Tick() {};
    friend class Entity;

public:
    int componentID; // This is originally private, we set it to public in order to test the mentioned system
    Component();
    inline int GetID() { return componentID; }
};

在 main() 内部:

    Component c = Component();
    std::cout << (&c + 1) << std::endl;
    std::cout << "component address: " << &c << "   offset size: " << offsetof(Component, componentID)
        << "    component address + offset: " << (&c + offsetof(Component, componentID)) 
        << "    component id address: " << &c.componentID << std::endl;

我看到很多论坛都推荐 offsetof(),我的经验如下:

有没有人知道如何忽略/跳过虚拟并能够根据其地址操纵成员值?

标签: c++memorymemory-addressvirtual-functions

解决方案


推荐阅读