Static只是一个可见性声明。
在Class或Struct外部的Static变量
-
仅对Link内部可见,即只作用于当前翻译单元 - 只给自己使用的变量
-
实例验证:
创建Static.cpp文件,在其中输入
int s_var = 10;
在Main.cpp文件中,同时创建s_var同名变量
#include <iostream>
#define LOG(x) std::cout << x << std::endl;
int s_var = 5;
int main() {
LOG(s_var);
return 0;
}
发生Link错误,因为在全局当中存在两个同名变量,链接器不知道具体指向哪一个. 修改Static.cpp文件如下
static int s_var = 10;
控制台输出5,证明static确实只在当前翻译单元中可见。
如果想在Main.cpp文件当中使用Static.cpp文件定义的内容,那么可以使用extern关键字解决。具体代码为Static.cpp文件依旧为全局可见的变量
int s_var = 10;
Main.cpp文件中s_var变量加上extern关键字,相当于引用的作用
#include <iostream>
#define LOG(x) std::cout << x << std::endl;
extern int s_var;
int main() {
LOG(s_var);
return 0;
}
控制台输出10.
- 除非需要跨单元编译,最好将函数和变量声明为Static. 安全性更有保障,同时避免出现一些不必要的链接错误。
在Class或Struct内部的Static变量
- 该变量将与类的所有实例共享内存 - 这个属性和实例无关,是所有对象共有的
#include <iostream>
struct Entity {
int x, y;
void Print() {
std::cout << x << "," << y << std::endl;
}
};
int main() {
Entity e;
e.x = 3;
e.y = 4;
Entity e1;
e1.x = 5;
e1.y = 9;
e.Print();
e1.Print();
return 0;
}
控制台输出3,4和5,9;
将Entity当中的x, y更新为Static,同时需要将Struct/Class内部的Static变量在类外定义
#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 = 3;
e.y = 4;
Entity e1;
e1.x = 5;
e1.y = 9;
e.Print();
e1.Print();
}
**控制台输出5,9和5,9. ** 因为Static变量,所有实例访问的都是同一个内存。
规范的写法,包括Static函数也是这样写,如果要更新值或者调用,先写作用域(Struct/Class名称):: 方法名/变量名.
#include <iostream>
struct Entity {
static int x, y;
static void Print() {
std::cout << x << "," << y << std::endl;
}
};
int Entity::x;
int Entity::y;
int main() {
Entity::x = 3;
Entity::y = 4;
Entity::Print();
e.Print();
}
- 静态方法无法访问非静态变量
非静态方法创建时,实际上是隐含着传递了参数:
void Print(Entity e){
std::cout << e.x << "," << e.y << std::endl;
}
静态方法则是不传递隐含的参数:
static void Print(){
std::cout << x << "," << y << std::endl;
}
这样我们必然不知道调用的x和y是什么。
- 在函数中添加Static变量,该变量的作用周期是从项目起到项目止。不会随着函数的结束而结束。
2130

被折叠的 条评论
为什么被折叠?



