应该在哪里“包括”放在C ++中 [英] where should "include" be put in C++

查看:104
本文介绍了应该在哪里“包括”放在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些c ++代码,请注意头文件和.cpp文件中都有#include。我想如果我移动文件中的所有#include,让我们说foo.cpp,它的'头文件foo.hh,让foo.cpp只包含foo.hh,代码应该工作,无论如何不考虑像缺点,效率等等。

I'm reading some c++ code and Notice that there are "#include" both in the header files and .cpp files . I guess if I move all the "#include" in the file, let's say foo.cpp, too its' header file foo.hh and let foo.cpp only include foo.hh the code should work anyway taking no account of issues like drawbacks , efficiency and etc .

我知道我的突然的想法在某种程度上是一个坏主意,但它的确切缺点是什么?我是c ++的新手,所以在我自己回答这个问题之前,我不想阅读很多C ++书。所以请在这里提出问题以寻求帮助。提前谢谢。

I know my "all of sudden" idea must be in some way a bad idea, but what is the exact drawbacks of it? I'm new to c++ so I don't want to read lots of C++ book before I can answer this question by myself. so just drop the question here for your help . thanks in advance.

推荐答案

通常情况下,尽可能将包含放在.cpp文件中,并且只在.cpp文件中。 h文件,如果不可能。

As a rule, put your includes in the .cpp files when you can, and only in the .h files when that is not possible.

您可以使用转发声明在许多情况下,不需要包含来自其他标头的标头:这可以帮助减少编译时间,这可能会随着项目的增长而成为一个大问题。这是一个很好的习惯,因为尝试在以后解决它(当它已经存在问题时)可能是一个彻头彻尾的噩梦。

You can use forward declarations to remove the need to include headers from other headers in many cases: this can help reduce compilation time which can become a big issue as your project grows. This is a good habit to get into early on because trying to sort it out at a later date (when its already a problem) can be a complete nightmare.

异常这个规则是模板化的类(或函数):为了使用它们,你需要看到完整的定义,这通常意味着将它们放在头文件中。

The exception to this rule is templated classes (or functions): in order to use them you need to see the full definition, which usually means putting them in a header file.

这篇关于应该在哪里“包括”放在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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