WHCSRL 技术网

C++学习篇:static局部静态对象

  1. #include <iostream>
  2. using namespace std;
  3. size_t count_calls()
  4. {
  5. static size_t ctr = 0;
  6. return ++ctr;
  7. }
  8. int main()
  9. {
  10. for (size_t i = 0; i != 10;i++)
  11. cout << count_calls() << endl;
  12. return 0;
  13. }

程序将输出1~10的数字,程序运行时每次static变量都会保存上一次的值。