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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP