作用
- 隐藏
不论是
static函数
orstatic变量
,当多个文件被同时编译的时候,所有没有static前缀
的全局变量和函数都有全局可见性
。
- 保持变量内容的持久
如果一个变量存储在
静态数据区
,那么它会在程序刚开始运行的时候就完成初始化
,这也是唯一的一次初始化。
- 一共有2种变量存储在
静态存储区
:全局变量和static变量。
- 默认初始化为
0
这个是针对
static变量
而言的。全局变量也会初始化为0
,因为在静态数据区
,内存中所有的字节默认值均是0x00
。
- C++的类成员声明
static
实战
- 函数中的静态变量
代码
#include <iostream>
#include <string>
using namespace std;
void demo()
{
static int cnt = 0;
cout << cnt << ' ';
cnt ++;
}
int main()
{
for (int i = 0; i < 5; i ++ ) demo();
return 0;
}
- 类中的静态变量
类中的静态变量应该是用户使用
类外的类名和范围解析运算符
显式初始化
代码
#include <iostream>
using namespace std;
class Apple
{
public:
static int i;
Apple ()
{
};
};
int Apple::i = 1;
int main()
{
Apple obj1;
Apple obj2;
Apple obj;
cout << obj.i << endl;
obj1.i = 2;
obj2.i = 3;
cout << obj1.i << endl << obj2.i << endl;
}
输出
image.png
image.png
- 类对象为静态
- 对象是非静态的
#include <iostream>
using namespace std;
class Apple
{
int i;
public:
Apple ()
{
i = 0;
cout << "Inside Ctor\n";
}
~Apple ()
{
cout << "Inside Dtor\n";
}
};
int main()
{
int x = 0;
if (x == 0) Apple obj;
cout << "End of main\n";
}
输出
image.png
- 将对象变成静态后
#include <iostream>
using namespace std;
class Apple
{
int i;
public:
Apple ()
{
i = 0;
cout << "Inside Ctor\n";
}
~Apple ()
{
cout << "Inside Dtor\n";
}
};
int main()
{
int x = 0;
if (x == 0) static Apple obj;
cout << "End of main\n";
}
输出
image.png
产生这样的原因是静态对象的范围是贯穿整个程序的生命周期的,所以要在main()结束后才调用
dtor
,非静态对象的范围只在if () Apple obj
内部,所以结束后先调用的dtor
。
- 类中的静态函数
对于静态成员函数,可以直接使用类名和范围解析运算符调用,如果是非静态成员函数,这样则会报错。
#include <iostream>
using namespace std;
class Apple
{
public:
static void printMsg()
{
cout << "Welcome to Apple!";
}
};
int main()
{
Apple::printMsg();
}