C ++中的静态存储类

静态存储类指示编译器在程序的生存期内保留局部变量,而不是在每次进入和超出范围时都创建并销毁它。因此,将局部变量设为静态允许它们在函数调用之间保持其值。

静态修饰符也可以应用于全局变量。完成此操作后,它将导致该变量的作用域仅限于声明该变量的文件。

在C ++中,当对类数据成员使用static时,它将导致该类的所有对象仅共享该成员的一个副本。

示例

#include <iostream>
void func( void ) {
   static int i = 10; // local static variable
   i++;
   std::cout << "i is " << i ;
   std::cout << " and count is " << count << std::endl;
}

static int count = 6; /* Global variable */

int main() {
   while(count--)
   {
      func();
   }
}

输出结果

这将给出输出-

i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0