避免头文件的循环依赖 [英] Avoiding Circular Dependencies of header files

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

问题描述

关于如何避免头文件的循环依赖,您有什么好的建议吗?

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.

是否有任何通用的、经过验证的和有效的规则?谢谢.

推荐答案

如果你有循环依赖,那么你就做错了.

If you have circular dependency then you doing something wrong.

例如:

foo.h
-----
class foo {
public:
   bar b;
};

bar.h
-----
class bar {
public:
   foo f;
};

你可能想要的是非法的:

Is illegal you probably want:

foo.h
-----
class bar; // forward declaration
class foo {
   ...
   bar *b;
   ...
};

bar.h
-----
class foo; // forward declaration
class bar {
   ...
   foo *f;
   ...
};

这没关系.

一般规则:

  1. 确保每个标题都可以单独包含.
  2. 如果您可以使用前向声明,请使用它们!

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

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