C++ 中的 static 儲存類


static 儲存類指示編譯器在程式的生命期內保持區域性變數的存在,而不是在區域性變數進入或退出作用域時不斷建立和銷燬它。因此,使得區域性變數在函式呼叫之間保持其值。

static 修飾符還可以應用於全域性變數。如果這樣做了,它將導致該變數的作用域限制在其宣告所在的範圍內。

在 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.