C++,两个有共同需求的类

标签 c++ circular-dependency

我已将一个科学模拟平台从 Java 转换为 C++。我试图使设计尽可能与以前的实现相同。在 java 中,由于后期绑定(bind),循环依赖在运行时被解析。然而,循环依赖在 C++ 中造成了困惑。

  1. 是否有分析和列出循环包含和引用的自动化工具? (Visual Studio 2010 只发出大量无意义的错误)。

  2. 我尝试尽可能使用前向引用。然而在某些情况下,两个类都需要另一个类的功能(即调用方法,这使得无法使用前向引用)。这些需求存在于 Logic 中,如果我从根本上改变设计,它们将不再代表现实世界的交互。

    我们如何实现两个需要彼此方法和状态的类?是否可以在 C++ 中实现它们?

示例:

  • 示例 1:我有一个名为“World”的类,它创建“Agent”类型的对象。代理需要调用 World 方法来获取其环境的信息。 World 还需要遍历 Agent 并执行它们的“run”方法并获取它们的状态(状态更新可能会反向完成以解决这部分问题,而不是 run 方法)。
  • 示例 2:代理创建其“意图”的集合。每个代理都需要遍历其意图和运行/更新/读取意图状态。 Intentions 还需要通过 Agent 获取有关环境的信息(如果直接通过“World”完成,它将再次创建复杂的圈子)以及 Agent 本身的信息。

下图显示了类的子集,以及它们的一些方法和属性:

sub-set of classes, and some of their methods and properties

最佳答案

我没有看到前向声明对您不起作用。看起来你需要类似的东西:

世界.h:

#ifndef World_h
#define World_h

class Agent;

class World
{
    World();
    void AddAgent(Agent* agent) { agents.push_back(agent); }
    void RunAgents();
private:
    std::vector<Agent*> agents;
};

#endif

代理.h:

#ifndef Agent_h
#define Agent_h

class World;
class Intention;

class Agent
{
    Agent(World& world_): world(world_) { world.AddAgent(this); }
    status_t Run();
private:
    World& world;
    std::vector<Intention*> intentions;
};

#endif

世界.cc:

#include "World.h"
#include "Agent.h"

void World::RunAgents()
{
    for(std::vector<Agent*>::iterator i = agents.begin(); i != agents.end; ++i)
    {
        Agent& agent(**i);
        status_t stat = agent.Run();
        // do something with stat.
    }
}

// ...

代理.cc:

#include "Agent.h"
#include "World.h"
#include "Intention.h"

// ...

关于C++,两个有共同需求的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10979031/

相关文章:

c++ - 使用同一泰勒级数评估log(1 + x)的递归

c++ - "Expected initializer before ' : ' token" with range-based for

mysql - 3 个表之间的循环连接(或嵌套连接)

javascript - 如何在Node.js中设置交叉同步? (相关循环依赖)

c++ - C++ 程序中使用的 SQL 数据类型是什么?

c++ - OpenGL光照和发光

c++ - 将数据从 NodeJS 传输到 C++ 应用程序

C++ 与嵌套类的循环依赖

java - 如何在循环链表中插入字符串(我想检查循环链表中的重复单词)?

delphi - 两个类有两个循环引用