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