我已经将科学的仿真平台从Java转换为C ++。我试图尽可能地保持设计与之前的实现相同。在java中,由于后期绑定,循环依赖项在运行时被解析。然而,循环依赖在C ++中造成了一团糟。
是否有自动化工具可以分析和列出循环包含和参考? (Visual Studio 2010仅发出大量无意义错误。)
我试图尽可能使用前向引用。然而,在某些情况下,两个类都需要另一个类的功能(即调用方法,这使得无法使用前向引用)。这些需求存在于Logic中,如果我从根本上改变设计,它们将不再代表真实世界的交互。
我们怎样才能实现两个需要彼此方法和状态的类?是否可以在C ++中实现它们?
示例:
下图显示了一个类的子集,以及它们的一些方法和属性:
答案 0 :(得分: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
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
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.
}
}
// ...
Agent.cc:
#include "Agent.h"
#include "World.h"
#include "Intention.h"
// ...
答案 1 :(得分:3)
你可以只使用前向声明来解决问题,但是你可能没有将实现与类的声明分开。
如果需要从类中调用方法,则需要完整类型,这就是您需要包含该文件的原因。您可以将文件包含在cpp
(实现文件)中,而不必担心循环依赖性。