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();
}