避免头文件的循环依赖
对于如何避免头文件的循环依赖,您有什么好的建议吗?
当然,从一开始,我就尝试将项目设计得尽可能透明。然而,随着越来越多的功能和类被添加,并且项目变得越来越不透明,循环依赖关系开始发生。
是否有任何通用的、经过验证的、有效的规则?谢谢。
Do you have any good advice on how to avoid circular dependencies of header files, please?
Of course, from the beginning, I try to design the project as transparent as possible. However, as more and more features and classes are added, and the project gets less transparent, circular dependencies start happening.
Are there any general, verified, and working rules? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
取决于您的预处理器功能:
或者
如果您发现设计头文件非常无聊,可能是makeheaders您可能会对 Hwaci(SQLite 和化石 DVCS 的设计者)感兴趣。
depending on your preprocessor capabilities:
or
If you find it very boring to design header files maybe makeheaders from Hwaci (designers of SQLite and fossil DVCS) could be of interest for you.
您的目标是分层方法。您可以定义模块可以依赖于较低层模块的层,但相反应该使用观察者< /a>。现在,您仍然可以定义层的细粒度以及是否接受层内的循环依赖关系,但在这种情况下,我将使用 这个。
What you're aiming at is a layered approach. You can define layers where modules can depend on lower layer modules but the inverse should be done with observers. Now you can still define how fine-grained your layers should be and whether you accept circular dependency within layers, but in this case I would use this.
一般来说,头文件应尽可能向前声明而不是包含其他头文件。
还要确保每个标头坚持一个类。
那么你几乎肯定不会出错。
最糟糕的耦合通常来自于臃肿的模板代码。因为必须在标头中包含定义,所以通常会导致必须包含各种标头,然后使用模板的类包含模板标头,包括大量其他内容。
出于这个原因,我通常会说:小心模板!理想情况下,模板不应在其实现代码中包含任何内容。
In general header files should forwardly declare rather than include other headers wherever possible.
Also ensure you stick to one class per header.
Then you almost certainly will not go wrong.
The worst coupling usually comes from bloated template code. Because you have to include the definition inside the header, it often leads to all kinds headers having to be included, and then the class that uses the template includes the template header, including a load of other stuff.
For this reason, I would generally say: be careful with templates! Ideally a template should not have to include anything in its implementation code.
尽管 Artyom 提供了最佳答案,但本教程也很棒,并提供了一些扩展 http://www.cplusplus。 com/forum/articles/10627/
Altough Artyom provided best answer this tutorial is also great and provides some extenstions http://www.cplusplus.com/forum/articles/10627/
如果你有循环依赖,那么你做错了什么。
例如:
是非法的,您可能想要:
这没关系。
一般规则:
If you have circular dependency then you doing something wrong.
As for example:
Is illegal you probably want:
And this is ok.
General rules:
#include "myclass.h"
成为myclass.cpp
中的第一个包含内容。#include "myclass.h"
the first include inmyclass.cpp
.我为避免循环依赖而遵循的一些最佳实践是:
Some best practices I follow to avoid circular dependencies are,
一般方法是将共性分解到第三个头文件中,然后由两个原始头文件引用。
另请参阅循环依赖最佳实践
A general approach is to factor out the commonalities into a third header file which is then referenced by the two original header files.
See also Circular Dependency Best Practice