C ++中的循环依赖性 [英] Circular Dependency in C++

查看:197
本文介绍了C ++中的循环依赖性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实:


  • 我有两个主要类别:经理和专家。

  • 是几种不同类型的专家。

  • 专家通常需要其他专家的协助才能完成工作。

  • 经理知道所有的专家,只知道他们的经理。 (这是问题。)

  • 在运行时,管理器创建并存储专家列表。然后,Manager循环遍历该列表,并请求每个专家进行初始化。在初始化期间,每个专家要求经理为他们提供满足一些描述的其他专家。一旦完成,经理就会进入一个循环,在此循环中专家被要求按顺序执行他们的专业任务。

  • I have two predominant classes: Manager and Specialist.
  • There are several different types of Specialists.
  • Specialists often require the help of other Specialists in order to get their job done.
  • The Manager knows all of the Specialists, and initially each Specialist knows only their Manager. (This is the problem.)
  • At runtime, the Manager creates and stores a list of Specialists. Then the Manager iterates through the list and asks each Specialist to initialize. During their initialization, each Specialist asks the Manager to supply them with other Specialists that fulfill some description. Once this is complete, the Manager then goes into a loop during which the Specialists are asked sequentially to perform their specialized task.

这似乎是一个体面的模式,但由于经理有专家名单和专家有经理我得到循环依赖问题。

To me it seems that this is a decent pattern, but since a Manager has a list of Specialists and a Specialist has a Manager I'm getting circular dependency problems.

这是一个情况,我应该以某种方式向前宣布一个类的存在从另一个? (如果是这样,怎么样?)或者我应该使用一些设计模式来解决这个问题吗? (如果是这样什么?)也...我虽然模式本身是漂亮的o.k。所以我不介意有人帮我理解为什么这是一件坏事。

Is this a case where I should somehow forward declare the existence of one class from another? (If so, how?) Or should I use some design pattern to fix this problem? (If so what?) Also... I though the pattern itself was pretty o.k. so I wouldn't mind someone helping me understand why this is a bad thing.

推荐答案

类:

Manager.h

class Specialist;

class Manager
{
    std::list<Specialist*> m_specialists;
};

Specialist.h

class Manager;

class Specialist
{
    Manager* m_myManager;
};

只有当你需要引入一个类的头文件时,成员函数或变量,或者需要使用类作为值类型等。当你只需要一个指针或引用一个类,一个向前的声明就足够了。

The only time you need to bring in the header file for a class is when you need to use a member function or variable within that class, or need to use the class as a value type etc. When you only need a pointer or reference to a class, a forward declaration will suffice.

请注意,转发声明不仅仅用于解决循环依赖。你应该尽可能使用转发声明。

Note that forward declarations aren't just for solving circular dependencies. You should use forward declarations wherever possible. They are always preferable to including an extra header file if it is at all viable.

这篇关于C ++中的循环依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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