前言
总结static关键字的作用
- 定义static变量意味只能在本.c/.cpp文件中使用该变量,而不能被其他.c/.cpp文件使用。
- 定义的static变量存储在静态区,所以只初始化一次,其生命周期较长,从程序开始直至结束。
- 定义static函数,意味只能在本.c/.cpp文件中使用该函数,而不能被其他.c/.cpp文件使用,可防止命名冲突。
(定义的函数默认是extern的。)
不能重复定义变量或函数,但是可以多次声明。
全局变量的作用范围为全局,即所有文件都可用,也即全局变量只能定义一次。
普通函数
- 函数域中的静态变量存储在静态区
int& StaticFun()
{
static int static_val = 0;
return static_val;
}
int main()
{
int& sa = StaticFun();
sa = 45;
sa = StaticFun();
cout << sa << endl; //45
}
函数名前加static 内部函数
作用域局限在定义函数的文件内(在其他文件就不能调用此函数了)
函数名前加extern 外部函数
作用域扩展到定义函数的文件外(在其他文件也可以调用此函数)
类
xx.h
class XX
{
public:
static const int xx_static_cival = 98; // 静态常量直接在类中初始化
static int xx_static_i; // 静态变量再此声明
static void fun(); // 静态函数没有this指针
};
xx.cpp
int XX::xx_static_i = 1; // 在此处定义和初始化
void XX::fun()
{
// 只能用类中的静态变量
}
SingleTon
class SingleTon{
public:
static SingleTon&GetInstance() {
static SingleTon instance;
return instance;
}
private:
// make constructor and deconstrucotor private
SingleTon () {}
~SingleTon() {}
SingleTon(const SingleTon&) = delete;
SingleTon&operator=(const SingleTon&) = delete;
};
//使用:
SingleTon& obj = SingleTon::GetInstance();

1574

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



