为什么此标头编译时缺少 #include

Why does this header compile with a missing #include?

本文关键字:#include 编译 为什么      更新时间:2023-10-16

Person.h

#ifndef PERSON_H_
#define PERSON_H_
/* Person.h */
class Person {
  int age;
  std::string name;
  public:
    Person(int, std::string);
    std::string getName();
    int getAge();
};
#endif /* PERSON_H_ */

person(int std::string) 函数声明使用 std::string 名称,但我没有将其包含在头文件中。 因此,我希望编译器会抱怨缺少符号。 然而,它可以编译和运行良好! 为什么?

代码的其余部分...

人.cpp

#include <string>
#include "Person.h"
Person::Person(int age, std::string name)
{
  this->name = name;
  this->age = age;
}
std::string Person::getName()
{
  return this->name;
}
int Person::getAge()
{
  return this->age;
}

主.cpp

#include <string>
#include "Person.h"
int main() {
  printFunc();
  Person chelsea_manning(5, std::string("Chelsea Manning"));
}

另外,我是C++新手,所以如果您发现我的代码/OOP有任何奇怪之处,请告诉我。

程序的编译从包含main函数的文件顶部开始(从技术上讲,预处理器在程序编译之前运行,但它仍然在同一个地方启动)。在您的情况下,它要做的第一件事是将<string>包含在该文件中。然后它包括 Person.h .由于已包含<string>,因此字符串文件的所有内容都位于代码中的 person 文件之前,并且所有内容都按正确的顺序声明。如果要在<string>之前包含Person.h,或者不在主文件中包含<string>,则确实会收到编译错误。

#include方向就像复制/粘贴一样:它从字面上读取<string>文件并将其内容拍打到包含它的源文件中。接下来,对Person.h做同样的事情。所以运行预处理器后的最终结果是

<-- contents of <string> -->
<-- contents of Person.h -->
int main()
...

因此,在您的示例中,所有内容都以正确的顺序声明。