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

更新時間: 2020 年 2 月 10 日

494 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.