【发布时间】:2020-09-22 21:03:32
【问题描述】:
是否需要将函数声明放在头文件中并将它们的定义放在源文件中?这样做有什么性能提升,或者可能有什么好处,而不是将声明和定义放在同一个文件中?示例:
在 Person.h 中
class Person() {
public:
void sayHi();
}
在 Person.cpp 中
#include "Person.h"
#include <cstdio>
void Person::sayHi() {
printf("Hello, world!\n");
}
而不是将其放在一个文件中:
#include <cstdio>
class Person {
void sayHi() {
printf("Hello, world!\n");
}
}
【问题讨论】:
-
不需要。无论哪种方式,都没有性能优势(对可执行文件)。请查看“编译单元”。
-
您设想在您的单文件版本中使用哪个文件?它会像头文件一样,为每个使用该函数的源文件读取吗?就像源文件一样,没有其他源文件可以看到其中的内容?
标签: c++ function header-files