自动定期使用static

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值