1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
void IncrementAndPrint()
{
using namespace std;
int nValue = 1; // automatic duration by default
++nValue;
cout << nValue << endl;
} // nValue is destroyed here
int main()
{
IncrementAndPrint();
IncrementAndPrint();
IncrementAndPrint();
}
每一次incrementandprint称,一个变量值是创造和分配价值的1。incrementandprint增量值为2,然后打印的值为2。当incrementandprint结束运行时,变量超出范围并被销毁。因此,该程序的输出:
2
2
2
现在考虑这个计划的固定范围的版本。这和上面的程序之间唯一的区别是,我们已经改变了局部变量的值自动定期使用static关键字。
固定的持续时间(使用static关键字):|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
void IncrementAndPrint()
{
using namespace std;
static int s_nValue = 1; // fixed duration
++s_nValue;
cout << s_nValue << endl;
} // s_nValue is not destroyed here, but becomes inaccessible
int main()
{
IncrementAndPrint();
IncrementAndPrint();
IncrementAndPrint();
}
本文通过两个示例对比了C++中自动变量与静态变量的行为差异。首先介绍了一个每次调用都会重新创建并初始化的自动变量,其值在每次函数调用结束后会被销毁。接着展示了如何使用静态变量来保留函数间的状态,即变量仅初始化一次并在各次函数调用间保持其值不变。
1246

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



