为什么此标头编译时缺少 #include
Why does this header compile with a missing #include?
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()
...
因此,在您的示例中,所有内容都以正确的顺序声明。
相关文章:
- 解析问题 - 预期的非限定 ID - #include <array> 编译错误
- 我可以在Visual Studio C++中使用 #include "pch.h" 而不是 #include "stdafx.h" 作为我的预编译头吗?
- C++:如果未找到文件,则进行编译时 #Include 处理
- 代码::块 (MinGW) #include <priority_queue>上的编译错误
- #define xyz在#include预编译标题之前
- 如何在OSX上为clang编译 #include < 实验/任意>
- C++程序在 #include 时无法编译<stack>,#include<queue>
- 如何使用 g++6 使用 std::reduce 和 #include 编译代码<execution_policy>?
- #include 多个.cpp中的标准文件,与将其 #include 在预编译标头中会影响可执行文件的大小?
- 编译时得到错误:找不到'QtGui/QAction'文件 #include < QtGui/QAction>
- 视觉C++ 尝试编译 gstreamer 应用程序时出现的问题 #include < anyfile.h>
- #include < mysql.h> & #include <my_global.h> 导致编译错误
- 为什么此标头编译时缺少 #include
- 使用 #include <algorithm>的 C++ 编译错误
- 添加许多 -isystem include 指令是否会显著减慢编译过程
- include类并使用g++进行编译
- 在#include中获取当前编译单元名称
- Linux g++编译错误:/usr/bin/ld:找不到-l/usr/local/include
- 如何使用 #include <thread>编译代码
- #include在查找预编译头文件时跳过——查找预编译头文件时意外结束