在C++中创建头文件的方法是通过创建一个以.h为后缀的文件,并在其中定义所需的函数、类、变量等。通常在头文件中只包含声明(declaration),而不包含实现(implementation)。然后在源文件中包含该头文件,以便在源文件中使用其中定义的内容。例如,可以按照以下步骤创建一个头文件:
#ifndef EXAMPLE_H
#define EXAMPLE_H
void sayHello();
class MyClass {
public:
void doSomething();
};
#endif
#include "example.h"
#include <iostream>
void sayHello() {
std::cout << "Hello, world!" << std::endl;
}
void MyClass::doSomething() {
std::cout << "Doing something..." << std::endl;
}
#include "example.h"
int main() {
sayHello();
MyClass obj;
obj.doSomething();
return 0;
}
通过以上步骤,可以创建一个头文件并在C++程序中使用它定义的内容。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:c++导入头文件的方法是什么