1. extern 声明与 extern "C"
- extern 声明:仅声明变量或函数而不分配内存,通常用于头文件中共享全局变量或函数声明。
- extern "C":强制以 C 语言方式编译函数,避免 C++ 的名称修饰(name mangling)。常用于 C/C++ 混合编程。
#ifdef __cplusplus
extern "C" {
void c_style_function();
}
#endif
2. static、inline 与 const
- 限制作用域为当前源文件(文件作用域)。
- 静态成员变量需在类外定义,静态成员函数不能访问非静态成员。
- 建议编译器内联展开函数体,适用于短小且频繁调用的函数。
- 只能被常量对象调用,且不能修改成员变量(除非变量标记为
mutable)。
const 成员函数:
class ConstExample {
mutable int modifiable;
public:
void const_func() const {
modifiable = 1;
}
};
inline:
inline int add(int a, int b) {
return a + b;
}
static:
class Example {
public:
static int count;
static void print { }
};
Example::count = ;

