1.Static outside of Class(global variable)
https://www.bilibili.com/video/BV1VJ411M7WR?p=21
Static variables or functions outside of Struct or Class (global variable)
static的变量和函数只对当前文件可见 不使用static不同文件如果同名会报错 全局变量 可以被所有文件使用
You can't have two global variables with the same name.
如果在两个文件中定义了同名的全局变量 linker会报错
如果将其中一个extern另外一个 不会报错 并且可以使用那个变量

如果在test.cpp文件中的s_Variable 声明为static 在main.cpp可声明同名的变量 也不需要使用extern 使用了会报错 找不到这个变量

2.Static inside Class
https://www.bilibili.com/video/BV1VJ411M7WR?p=22
#include <iostream>
class People{
public:
static int x,y;
static void test_static(){
std::cout<<"x="<<x<<",y="<<y<<std::endl;
}//静态成员函数只能访问静态成员变量和静态成员函数
};
int People::x=5;
int People::y=6;//静态成员变量需要在类的外部进行定义和初始化
int main(){
People people1,people2;
std::cout<<People::x<<std::endl;
std::cout<<people1.y<<std::endl;
people2.y=8;
std::cout<<People::y<<std::endl;
People::test_static();
people1.test_static();
}
3.Static local variable
https://www.bilibili.com/video/BV1VJ411M7WR?p=23
这一集视频后面的那个singleton的例子为没有看懂
It doesn't matter if it is defined in a function or a class. They will only be accessible in their own scope. But the lifetime of those variables will be the same.

本文详细介绍了C++中的静态变量和函数的用法。静态全局变量限制了其在当前文件内的可见性,避免了同名变量冲突。静态成员变量在类中为所有实例共享,需要在类外初始化。静态局部变量则只在其作用域内存在,但生命周期贯穿整个程序运行。
1590

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



