Static有三个用途,分别是:
1:在类和结构体之外
表示只在当前文件内的全局变量,只能存在一个,在其他文件中不能重复声明。
void f(){
static int a = 0;
a++;
cout<<a<<endl;
};
调用这样的函数f()不会每次都将a重置为0,而是会每次自增。
2:在类和结构体之内
类似于“类变量”,所有的实例都可以共享这个static变量。
Class Player {
public:
static int health;
}
int Player::health = 100//一定要在类外初始化!
Player player1;
player1.health == Player::health;//True
//类名加双冒号,实例加点
3:延长生命周期
标识了static的对象会在main函数整个结束时才调用析构函数,并释放内存,这点和第一点类似。
Class Entity{
public:
Entity(){
cout<<"Entity created!"<<endl;
}
~Entity(){
cout<<"Entity destroyed!"<<endl;
}
};
int main(){
Entity e1;
static Entity e2;
cout<<"Main function ended"<<end;//实际这句输出在main生命周期结束之前,仅做演示用。
}
Output:
e1 created!
e2 created!
e1 destroyed!
Main function ended!
e2 destroyed!