#include <iostream>using namespace std;voID showLocal(); //Function prototypeint main(){ showLocal(); showLocal(); return 0;}voID showLocal(){ int localNum = 5; // Local variable cout << "localNum is " << localNum << endl; localNum = 99;}程序输出结果:
localNum is 5
localNum is 5
然而,有时候需要让程序“记住”在函数调用之间的局部变量中存储了什么值,这可以通过使变量成为静态变量来实现。当函数返回时,静态局部变量不会被销毁,它们存在于程序的整个一生中,尽管它们的作用域只是在定义它们的函数中。
下面的程序使用了静态局部变量来计算调用函数的次数:
#include <iostream>using namespace std;voID showStatic(); // Function prototypeint main(){ // Call the showStatic function five times for (int count = 0; count < 5; count++) showStatic(); return 0;}voID showStatic(){ static int numCalls = 0; // Static local variable cout << "This function has been called " << ++numCalls << " times." << endl;}程序输出结果:
This function has been called 1 times.
This function has been called 2 times.
This function has been called 3 times.
This function has been called 4 times.
This function has been called 5 times.
有人可能会认为每次调用 showStatic 函数时,numCalls 将被重新初始化为 0,但是不会发生这种情况,因为只有在创建该变量时才会初始化一个变量,而在程序运行期间静态变量只创建一次。如果没有初始化 numCalls,那么它将自动初始化为 0,因为和全局变量一样,如果程序员没有初始化数字静态局部变量,则它们将自动初始化为 0。
总结
以上是内存溢出为你收集整理的C++ static静态变量(无师自通)全部内容,希望文章能够帮你解决C++ static静态变量(无师自通)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)