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

wma*_*mac 12 c++ circular-dependency

我已经将Java的科学仿真平台转换为C++.我试图尽可能地保持设计与以前的实现相同.在java中,由于后期绑定,循环依赖项在运行时被解析.然而,循环依赖已经在C++中造成了一团糟.

  1. 是否有自动化工具可以分析和列出循环包含和参考?(Visual Studio 2010仅发出大量无意义错误).

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

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

例子:

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

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

类的子集,以及它们的一些方法和属性

Mik*_*one 17

我没看到前方声明对你没有用处.看起来你需要这样的东西:

World.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
Run Code Online (Sandbox Code Playgroud)

Agent.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
Run Code Online (Sandbox Code Playgroud)

World.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.
    }
}

// ...
Run Code Online (Sandbox Code Playgroud)

Agent.cc:

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

// ...
Run Code Online (Sandbox Code Playgroud)

  • 即使语言不需要它,但最好将所有包含放在文件的开头,以便有人阅读您的代码可以快速了解其依赖性. (3认同)