C++ 我可以(不)在.cpp文件中包含哪些内容?

C++ 我可以(不)在.cpp文件中包含哪些内容?,c++,include,header-files,C++,Include,Header Files,这个问题很奇怪。 假设我有一个名为idiot.cpp的文件,它的开头是: #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <string> #include <set> #include <exception> #include <iostream> #include "idiot.

这个问题很奇怪。 假设我有一个名为idiot.cpp的文件,它的开头是:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#include "idiot.h"
#包括
#包括
#包括
#包括
#包括
#包括
#包括“白痴,h”
我有一个头文件,傻瓜.h。首先,在白痴。h中,我也必须插入吗

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#包括
#包括
#包括
#包括
#包括
#包括
或者我没有? 其次,如果我有另一个源文件,比如说“bonito.cpp”,它使用了idiot.h,我应该只
#包括“idiot.h”
,还是应该再次粘贴代码段? 如果没有,有没有办法缩短这个长度,这样我就不会在每个文件中包含大约20个标题?(假设)
如果这是一个非常愚蠢的问题,很抱歉,但我不会经常使用太多的标题。

idiot.cpp
不需要包含由
idiot.h
间接包含的任何内容才能编译

更有趣的例子是:
bonito.cpp
#包括
s
idiot.h
idiot.h
包括
x.h
。如果
idiot.h
仅将
x.h
的内容用于私有或匿名命名空间代码,并且
bonito.cpp
也希望使用
x.h
中的内容,则
bonito.cpp
应直接(冗余)包含
x.h

理由很简单:
idiot.h
无法在不破坏客户端代码的情况下从公共/受保护的接口中删除某些内容,因此如果发生这种情况,客户端必须处理它-可能还包括一个额外的头。但是,
idiot.h
idiot.cpp
的维护者应该可以自由更改
idiot.h
中的私有或匿名命名空间内容,而不会破坏客户端代码,包括包含哪些头以支持该私有代码

因此,包含在完成时是多余的,但这样做的目的是,随着
idiot.h
的发展,它可能不再是多余的

此最佳实践模型不是自动强制执行的-您必须了解其工作方式,并主动为该模型编写代码

例子 如果
idiot.h
包含

#include <string>
#include <vector>
...
class X {
    void add(const std::string&);
  private:
    std::vector<std::string> v_;
};
#包括
#包括
...
X类{
void add(const std::string&);
私人:
std::向量v_;
};

…那么
bonito.cpp
可以合理地使用
std::string
而不包括
,但是如果它需要
std::vector
,如果idiot.h需要上面的头,因为没有它们就无法编译,那么idiot.h应该包括头。如果没有,则它们是cpp文件的实现细节,其他cpp文件不应包含其他头,除非它们还需要包含在中的声明和定义。将需要的内容放入头中,以便头中的声明成功。在.cpp文件中包含未在相应标头中指定的任何所需内容。不要包含不需要的内容。
.h
文件应该只包含它实际使用的东西所需的最低限度。
.cpp
文件应仅包含它所需的其他标题,而这些标题尚未包含在它所包含的其他标题中。太棒了,谢谢!现在我想起来,这是有道理的lol,比如为什么我在包含SDL2.h时不包含X11和其他一百万个东西。
idiot.cpp
只需要
idiot.h
,你在那里得到的丰富多彩的名字。谢谢。读到这个写得很好的答案,还有我愚蠢的文件名,真是有点好笑哈哈