static 关键字
-
将具有 外部链接 属性的变量/函数转换为 内部链接
全局变量和函数的链接属性默认为外部链接(对其他文件可见)
我们在
test.cpp
文件中定义全局变量global
,并申明函数func()
test.cpp
#include<iostream> using namespace std; void func(); int global = 0; int main() { func(); // 调用 test2.cpp 中定义的 func 函数 }
在
test2.cpp
文件中定义函数func()
并声明变量global
test2.cpp
#include<iostream> extern int global; void func() { // 使用 test.cpp 中定义的 global 变量 std::cout << "global int test2.cpp: " << global << std::endl; }
编译两个文件并运行,得到输出:
global int test2.cpp: 0
现在我们使用
static
声明函数和变量:static int global = 0; static void func() { std::cout << "global int test2.cpp: " << global << std::endl; }
编译发现报错:
错误 LNK2019 无法解析的外部符号 "void __cdecl func(void)" (?func@@YAXXZ),函数 _main 中引用了该符号 错误 LNK2001 无法解析的外部符号 "int global" (?global@@3HA)
此时
global
对test2.cpp
是不可见的;func()
函数对test.cpp
是不可见的 -
将具有 自动存储期限 的变量转换为 静态存储期限
auto变量(函数局部变量)都是在栈内存区存放,函数结束后就自动释放。但是全局的和函数内定义的static变量都是存放在数据区的,且只存一份,只在整个程序结束后才自动释放。
void func() { // static 类型变量只在程序第一次执行到定义时初始化 static int i = 0; int j = 0; cout << "i = "<< i++ << " j = " << j++ << endl; } int main() { func(); func(); func(); }
输出:
i = 0 j = 0 i = 1 j = 0 i = 2 j = 0
-
C++ 中 静态成员变量 :整个类共享。必须在类外定义
class A { private: int _i; static int _si; public: static int _hi; static void print(); void show(); }; // 只有定义时可以使用 类名:: 访问到,其他时候不可以 int A::_si = 10; int A::_hi = 20; int main() { A a; // 不在类外定义,会报连接错误 cout << A::_hi