c++的头文件使用
👍 下面是每种在头文件中常见内容的示例写法(C++标准格式):
✅ 1. 函数声明
// 函数声明(不定义函数体)
int add(int a, int b);
double getAverage(double x, double y);
✅ 2. 类声明
// 类声明(仅定义接口,不写函数体)
class Student {
public:void setName(const std::string& name);std::string getName() const;
private:std::string name;
};
✅ 3. 常量定义
在头文件中推荐使用
constexpr或const,而不是#define。
const double PI = 3.14159;
constexpr int MAX_SIZE = 100;
✅ 4. 宏定义
宏是预处理器指令,不建议滥用。
#define DEBUG_MODE
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
✅ 5. 模板定义
// 函数模板
template <typename T>
T add(T a, T b) {return a + b;
}// 类模板
template <typename T>
class Box {
public:T value;Box(T v) : value(v) {}
};
✅ 6. 内联函数
inline int multiply(int a, int b) {return a * b;
}
✅ 7. 类型别名
typedef unsigned int uint;     // 旧写法
using uint32 = unsigned int;   // 推荐的新写法 (C++11 起)
using StringList = std::vector<std::string>;
