自动定期使用static

来源:互联网 发布:预科生的贩毒网络免费 编辑:程序博客网 时间:2024/06/08 08:02
12345678910111213141516#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关键字

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


0 0
原创粉丝点击