gpt4 book ai didi

c++ - header 在 C++ 中包含 Creep

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:49 25 4
gpt4 key购买 nike

当我开始学习 C++ 时,我了解到头文件通常应该#included 在其他头文件中。刚才有人告诉我,我应该在我的 .cpp 文件中包含一个特定的头文件,以避免头文件包含蠕变。

谁能告诉我这到底是什么,为什么会出现问题,并可能会告诉我一些文档,说明何时我想在另一个 header 中包含一个文件,以及何时应该在 .cpp 文件中包含一个文件?

最佳答案

“蠕变”是指包含一个 header ,其中包含许多其他 header 。这会产生一些不良后果:

  • 倾向于每个源文件都间接包含每个头文件,因此对任何头文件的更改都需要重新编译所有内容;
  • 更有可能导致心痛的循环依赖。

您通常可以通过仅声明所需的类而不是包含提供完整定义的 header 来避免包含另一个 header 。这种不完整类型可以以多种方式使用:

// Don't need this
//#include "thingy.h"

// just this
class thingy;

class whatsit {

// You can declare pointers and references
thingy * p;
thingy & r;

// You can declare static member variables (and external globals)
// They will need the header in the source file that defines them
static thingy s;

// You can declare (but not define) functions with incomplete
// parameter or return types
thingy f(thingy);
};

有些事情确实需要完整的定义:

// Do need this
#include "thingy.h"

// Needed for inheritance
class whatsit : thingy {

// Needed for non-static member variables
thingy t;

// Needed to do many things like copying, accessing members, etc
thingy f() {return t;}
};

关于c++ - header 在 C++ 中包含 Creep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28903941/

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