C ++,两个有共同需要的类 [英] C++, two classes with mutual needs

查看:81
本文介绍了C ++,两个有共同需要的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将科学仿真平台从Java转换为C ++。我试图使设计尽可能与以前的实现相同。在Java中,由于后期绑定,循环依赖项在运行时被解析。但是,循环依赖关系在C ++中造成了混乱。

I have converted a scientific simulation platform from Java into C++. I have tried to keep the design as much as possible the same as previous implementation. In java because of the late binding, circular dependencies are resolved at the run time. However, circular dependencies have created a hell of a mess in C++.


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

  1. Is there an automated tool which analyses and lists the circular includes and references? (Visual Studio 2010 only issues a huge list of nonsense errors).

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

I have tried to use forward references wherever possible. However in some occasions both classes need functionality of the other class (i.e. call to methods which makes it impossible to use forward reference). These needs exist in Logic and if I radically change the design they will no more represent real world interactions.

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

How could we implement two classes which need each other's methods and status? Is it possible to implement them in C++?

示例:


  • 示例1:我有一个名为 World的类,它创建类型为代理的对象。代理需要调用World方法来获取其环境信息。世界还需要遍历代理并执行它们的运行。方法并获取其状态(可能需要反向进行状态更新以解决此部分问题,而不是运行方法)。

  • 示例2:代理创建其意图的集合;。每个代理都需要遍历其意图以及运行/更新/读取意图状态。意图还需要通过代理获取有关环境的信息(如果直接通过世界直接完成,它将再次创建复杂的圆圈)以及代理本身的信息。

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

Below diagram shows a sub-set of classes, and some of their methods and properties:

推荐答案

I'我看不到前向声明对您不起作用。看来您需要以下内容:

I'm not seeing how forward declarations are not working for you. It looks like you need something like:

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"

// ...

这篇关于C ++,两个有共同需要的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆