事实:
对我来说,这似乎是一个不错的模式,但由于经理有专家列表,专家有经理,我遇到了循环依赖问题.
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++中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!