c++ - 如何在不需要对其他文件进行多次更改的情况下处理派生类的多个重载

标签 c++ oop inheritance overloading

我不确定如何表达这个问题的标题,但这是我的问题:

我正在使用实体组件系统架构在 C++ 中开发游戏。在此架构中,每个游戏对象都表示为一个类:

class Object

类只不过是组件的容器,它处理游戏对象的部分逻辑。

class Component

每个组件都有一个更新函数和特定事件的事件处理程序。每个事件都派生自一个公共(public)基类,每个子对象都有自己的数据字段来描述事件。在我的实际代码中,基本事件类有一些所有事件共享的属性。

class Event
{
};

class OnDeathEvent : public Event
{
public:
    int getKillerID() const
    {
        return 92341;
    }
};

class OnLevelEnterEvent : public Event
{
public:
    int getLevelEnteredID() const
    {
        return 100;
    }
};

在整个代码中,我们向对象发送事件。这是我为测试示例代码而编写的主要函数:

int main()
{
    Object obj;
    obj.sendEvent(OnLevelEnterEvent());
    obj.sendEvent(OnDeathEvent());
    std::cin.ignore();
    return 0;
}

当一个对象接收到一个事件时,它将对该事件的责任委托(delegate)给它的组件。

    for (auto& component : components)
    {
        component->handleEvent(e);
    }

我想为每个事件类型使用函数重载。事件处理函数的目的变得非常清晰。

void handleEvent(const OnLevelEnterEvent& e) 

但是这样做需要对象类和组件基类都声明每个事件类型的所有重载。显然,这是我们想要避免的事情,因为我们必须更改多个类才能将新的事件类型添加到我们的游戏中。这是示例代码的其余部分:

class Component
{
public:

    virtual void handleEvent(const Event& e) {}
    virtual void handleEvent(const OnDeathEvent& e) {};
    virtual void handleEvent(const OnLevelEnterEvent& e) {};
};

class TestComponent : public Component
{
public:
    virtual void handleEvent(const OnDeathEvent& e)
    {
        std::cout << "You died. Your killer was: " << e.getKillerID() << std::endl;
    }
};

class AnotherComponent : public Component
{
public:
    virtual void handleEvent(const OnLevelEnterEvent& e) 
    {
        std::cout << "Level Entered with ID: " << e.getLevelEnteredID() << std::endl;
    }
};

对象类:

class Object
{
public:
    Object() 
    {
        components.push_back(new TestComponent());
        components.push_back(new AnotherComponent());
    }


    void sendEvent(const Event& e)
    {
        for (auto& component : components)
        {
            component->handleEvent(e);
        }
    }

    void sendEvent(const OnDeathEvent& e)
    {
        for (auto& component : components)
        {
            component->handleEvent(e);
        }
    }

    void sendEvent(const OnLevelEnterEvent& e)
    {
        for (auto& component : components)
        {
            component->handleEvent(e);
        }
    }

private:
    std::vector<Component*> components;
};

我们希望能够通过从 Event 类继承来添加新的 Event 类型,而无需更改其他文件或创建新文件(新 Event 类除外)。什么是构建我们代码的优雅方式?

欢迎提出任何建议。

最佳答案

您的组件可以注册该事件。 当调用子事件时,它可以通知其已注册的事件监听器。您可以定义一个接口(interface)并使用接口(interface)继承。

关于c++ - 如何在不需要对其他文件进行多次更改的情况下处理派生类的多个重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378989/

相关文章:

ios - 从 Parent/Base 到 Child 类的 Swift Type Cast

java - eclipselink JPA : combining @MappedSuperclass with @Cacheable

具有相同方法名称的不同类的Java程序在继承的情况下

javascript - JS 中的方法链

java - 扩展多个类

c++ - 相当于 boost 分词器表达式/构造的 Qt

c++ - 服务没有及时响应启动或控制请求

c++ - 当我使用 SendInput 发送鼠标光标位置时屏幕变黑

c++ - Win32编程隐藏控制台窗口

c# - 为什么抽象类不能有密封方法