总结自Cherno
目录
一、类和结构体外的static
参考视频:【21】C++中的静态(static)_哔哩哔哩_bilibili
通过static关键字使变量仅可在该翻译单元可见
示例:
static.cpp
static int s_Variable = 5;
main.cpp
#include <iostream>
int s_Variable = 10;
int main(){
std::cout << s_Variable << std::endl;
}
输出结果:10
如果将static.cpp中的static去掉,则会在链接阶段报错:
错误 LNK2005 "int s_Variable" (?s_Variable@@3HA) 已经在 static.obj 中。
这是因为在项目中定义了两个相同的全局变量,通过static修饰,使其仅在static.cpp中可见。
为了解决上述报错,除static之外,还可以在main.cpp中用extern修饰。输出结果为5。
#include <iostream>
extern int s_Variable;
int main() {
std::cout << s_Variable << std::endl;
}
二、类和结构体内的static
通过static关键字修饰意味着该变量将与类的所有实例共享内存
示例1:
#include <iostream>
struct Entity
{
int x, y;
void print() {
std::cout << x << "," << y << std::endl;
}
};
int main() {
Entity e;
e.x = 2;
e.y = 3;
Entity e1 = { 5,8 };
e.print();
e1.print();
}
输出结果:
2,3
5,8
示例2:
#include <iostream>
struct Entity
{
static int x, y;
void print() {
std::cout << x << "," << y << std::endl;
}
};
int Entity::x;
int Entity::y;
int main() {
Entity e;
e.x = 2;
e.y = 3;
Entity e1;
e1.x = 5;
e1.y = 8;
e.print();
e1.print();
}
输出结果:
5,8
5,8
注:
1.e和e1两个不同实例中的x,y共享了一个内存,所以最后结果都是5,8
2.需要额外对x,y静态变量进行初始化
3.静态方法由于没有实例,所以不能访问非静态变量
4.非静态函数也不能访问静态变量
5.静态方法可以访问静态变量
三、C++中的局部静态
参考视频:【23】C++中的局部静态(Local Static)_哔哩哔哩_bilibili
示例:
#include <iostream>
void Function()
{
static int i = 0;
i++;
std::cout << i << std::endl;
}
int main()
{
Function();
Function();
Function();
Function();
Function();
}
输出结果:1,2,3,4,5
通过添加静态,将变量的生命周期延长到永远
相比全局变量,可以避免每个人都有访问它的权限
静态局部变量只会在程序的生命周期内初始化一次