在实现中包含头 [英] reincluding header in implementation

查看:121
本文介绍了在实现中包含头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个标头 foo.h ,例如:

suppose I have a header foo.h like this:

#ifndef FOO_H
#define FOO_H
#include <string>
#include "non_standard_class.h"

std::string foo(MyClass a);
...
#endif

> foo.cpp 将是

and the implementation foo.cpp will be

#include <vector>

#include "foo.h"

std::string foo(MyClass a)
{
   std::vector<int> x;
   MyClass b;
   ...
}

这是一个很好的原因重新包括< string> non_standard_class.h 位于 foo.cpp ?关键是:如果我阅读 foo.cpp ,我怎么能理解MyClass从哪里来?我需要查看 foo.h ,但会更困难。

is it a good pratice to re-include <string> and non_standard_class.h in foo.cpp ? The point is: if I read foo.cpp how can I understand where does MyClass come from? I need to look at foo.h but it will be more difficult.

推荐答案

我遵循的做法:


  • foo.h应该直接包含其源代码所需的所有标题(即 #include< string> 如果foo.h中有 std :: string

  • foo .cpp应该直接包括foo.h和其自己的源代码需要的所有其他头文件,除了那些已经被foo.h直接包含的头文件。

  • foo.h should directly include all headers its source code needs (i.e. #include <string> if there is std::string in foo.h)
  • foo.cpp should directly include foo.h plus all other headers its own source code needs, except for those already directly included by foo.h

这种做法的另一种表达形式:在foo。*中,只包括源代码所需的头文件。如果只有foo.cpp(而不是foo.h)需要一个头,那么从foo.cpp中包含它,否则从foo.h中包含它。

Another formulation of this practice: in foo.*, include only those headers the source code needs. If a header is needed by only foo.cpp (but not by foo.h), then include it from foo.cpp, otherwise include it from foo.h.

所以,在你的情况下,我不会在foo.cpp中 #include< string> ,因为它已经包含在foo.h中。

So, in your case, I wouldn't #include <string> in foo.cpp, because it's already included by foo.h.

让我们假设 string 有一个 #include< vector> 和foo。 h包含 std :: vector 。在这种情况下,我会在foo.h中 #include< vector> ,因为它的源代码需要它–并且 string 已经包含它并不重要。

Let's assume that string does an #include <vector>, and foo.h contains std::vector. In this case, I'd #include <vector> in foo.h, because its source code needs it – and it doesn't matter that string already includes it.

这篇关于在实现中包含头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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