Header 收录顺序混乱

Header inclusion order confusion

我有一个 header 文件,名为 Person.h:

class Person
{
    public:
        Person();
    private:
        std::string name;
};

实现在名为 Person.cpp:

的文件中
#include <string>
#include "Person.h"

Person::Person()
{
    name = "foo";
}

我习惯于避免嵌套包含文件,所以我先 #include-ing <string> header 然后再包含 class header class 源文件。

现在编译时不会出现 std::string 不是已定义名称的错误。但是,如果我将其包含在 header 文件中,它就会编译。

在网上我发现包含 headers,注意包含的顺序(这是我在 C 中经常做的,我的主要语言)确实应该有效(包含文件不是由他们自己,但只是插入到源文件中)。

所以我的问题是,为什么不在 header 文件中包含字符串 header 就无法编译?因为 header 文件是 "copy-pasted" 进入源文件 #include <string> 之后,我希望它编译得很好。

问题是 header 必须包含它所依赖的类型定义的 header,或者只需要一个指针和引用的 forward-declare 类型。

<string.h> 的内容移到您的 header 文件中以解决此问题。

您无需担心多重包含,因为所有标准 header 都使用 Inclusion Guards。您还需要为自己的 header 添加包含保护。

[needing to see forward declarations is] the same in C. But it should get them from the header file included before in the cpp file.

除了 Person.cpp 之外,您似乎还有其他地方包含 Person.h header 文件。这就是触发错误的原因。

您想像标准头文件和其他人一样使用,include guards

#ifndef PERSON_H
#define PERSON_H

/// your header file

#endif // PERSON_H

最好将您的 class 的所有相关 header 包含在 class 的 header 文件中。如果选择不这样做,则需要您记住在使用您的 class 的所有其他文件中包含必要的 header,并且当您向 class 添加新功能时,因此需要额外的 headers,然后你必须访问包含你的 class header 的每个地方,并将正确的 headers 添加到每个文件。