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

编程入门 行业动态 更新时间:2024-10-21 23:02:33
本文介绍了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++.

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

  • 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 ++,两个有共同需要的类

    本文发布于:2023-05-25 19:39:12,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/320937.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:两个

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!