C++中的循环依赖

Circular Dependency in C++(C++中的循环依赖)

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

问题描述

事实:

  • 我有两个主要类别:经理和专家.
  • 有几种不同类型的专家.
  • 专家通常需要其他专家的帮助才能完成工作.
  • 经理认识所有专家,最初每个专家只认识他们的经理.(这就是问题所在.)
  • 在运行时,管理器创建并存储专家列表.然后管理器遍历列表并要求每个专家进行初始化.在他们的初始化期间,每个专家要求经理为他们提供满足某些描述的其他专家.完成此操作后,经理会进入一个循环,在此过程中,专家会被依次要求执行他们的专业任务.

对我来说,这似乎是一个不错的模式,但由于经理有专家列表,专家有经理,我遇到了循环依赖问题.

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.

在这种情况下,我应该以某种方式向前声明另一个类的存在吗?(如果是这样,怎么做?)或者我应该使用一些设计模式来解决这个问题吗?(如果是什么?)另外……我虽然模式本身很不错.所以我不介意有人帮助我理解为什么这是一件坏事.

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.

推荐答案

在这两种情况下,向前声明另一个类:

In both cases, forward declare the other class:

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++中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++中的循环依赖

基础教程推荐