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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP