C++_CH16_Local static
C++_CH16_Local static
用static标注,使得变量成为局部变量
变量是有作用域的,比如函数可以是一个变量的作用域。能在整个工程使用的变量叫全局变量,其余的叫局部变量。举个例子
#include<iostream>
void printf()
{
int i = 0;
i++;
std::cout<<i<<std::endl;
}
int main()
{
printf();
printf();
printf();
printf();
printf();
std::cin.get();
}
output:
1
1
1
1
1
这是因为,每次调用printf(),i的值都被重新更改为了0。
1.2 解决方法
把int i = 0写在函数外面来
#include<iostream>
int i = 0;
void printf()
{
i++;
std::cout<<i<<std::endl;
}
int main()
{
printf();
printf();
printf();
printf();
printf();
std::cin.get();
}
output:
1
2
3
4
5
但是这个方法有个问题。一旦我们在main函数中对i进行修改,会改变局势的走向:(因为我们可以在任意位置访问i)
#include<iostream>
int i = 0;
void printf()
{
i++;
std::cout<<i<<std::endl;
}
int main()
{
printf();
printf();
i = 10;
printf();
printf();
printf();
std::cin.get();
}
output:
1
2
11
12
13
因此有了方法2:
#include<iostream>
void printf()
{
static int i = 0;
i++;
std::cout<<i<<std::endl;
}
int main()
{
printf();
printf();
printf();
printf();
printf();
std::cin.get();
}
output:
1
2
3
4
5
如果在任意位置修改i,则会报错。加上static后,重新调用一次函数,不会把i的值归0。
1.3 局部静态让代码更简洁
比如我要编写一个类:
#include<iostream>
class Singleton
{
private:
static Singleton* s_instance;
// 私有构造函数,防止外部创建实例
Singleton() {}
public:
// 延迟初始化单例对象
static Singleton& Get(){
if (s_instance == nullptr) {
s_instance = new Singleton();
}
return *s_instance;
}
void hello()
{
std::cout<<"Hello"<<std::endl;
}
};
// 静态成员的初始化
Singleton* Singleton::s_instance = nullptr;
int main()
{
Singleton::Get().hello();
std::cin.get();
return 0;
}
就可以直接这样写:
#include<iostream>
class Singleton
{
public:
static Singleton& Get()
{
static Singleton instance;
return instance;
}
void hello()
{
std::cout<<"Hello"<<std::endl;
}
};
int main()
{
Singleton::Get().hello();
std::cin.get();
return 0;
}
output:
Hello