gpt4 book ai didi

c++ - 我能(不能)在 .cpp 文件中包含什么?

转载 作者:行者123 更新时间:2023-12-01 14:22:47 26 4
gpt4 key购买 nike

这个问题很奇怪。假设我有一个名为 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"

我有一个头文件,idiot.h。首先,在 idiot.h 中,我是否也必须插入

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>

或者我不是?其次,如果我有另一个使用 idiot.h 的源文件,例如“bonito.cpp”,我应该只#include "idiot.h",还是应该再次粘贴代码片段?如果没有,有没有什么办法可以缩短它,这样我就不会在每个文件中包含大约 20 个标题? (假设)很抱歉,如果这是一个非常愚蠢的问题,但我不会经常使用许多 header 。

最佳答案

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

更有趣的案例:bonito.cpp #include s idiot.hidiot.h包括 x.h .如果idiot.h 使用x.h的内容用于私有(private)或匿名命名空间代码 - 和 bonito.cpp想使用来自 x.h 的东西也是,那么bonito.cpp应该包括 x.h直接(冗余)。

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

因此,包含在完成时是多余的,但这样做是因为期望它可能不再像 idiot.h 那样多余。进化。

此最佳实践模型不会自动执行 - 您必须了解它的工作方式并积极为该模型编写代码。

例子

如果idiot.h包含...

#include <string>
#include <vector>
...
class X {
void add(const std::string&);
private:
std::vector<std::string> v_;
};

...然后bonito.cpp可以合理使用std::string不包括 <string> , 但应包括 <vector>自己如果需要std::vector<> .

关于c++ - 我能(不能)在 .cpp 文件中包含什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62140312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com