C++中的靜態變量(static variable)具有內部鏈接性,這意味著它們只在定義它們的源文件中是可見的。靜態變量的值在程序的整個生命周期內保持不變,除非你顯式地修改它。靜態變量在程序啟動時初始化,并在程序結束時銷毀。
這里有一個關于C++靜態變量的簡單示例:
#include <iostream>
void myFunction() {
static int count = 0; // 靜態變量
count++;
std::cout << "This function has been called " << count << " times." << std::endl;
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
在這個示例中,count
是一個靜態變量,它在myFunction
中被遞增。每次調用myFunction
時,count
的值都會增加,但它的值在函數調用之間保持不變。因此,輸出將是:
This function has been called 1 times.
This function has been called 2 times.
This function has been called 3 times.