在C++中,靜態變量在程序啟動時初始化,只初始化一次。靜態變量的初始化有兩種方式:局部靜態變量和全局靜態變量。
在函數內部定義的靜態變量,它在第一次調用該函數時被初始化,之后每次調用函數時不再重新初始化,而是保持上一次調用結束時的值。局部靜態變量的初始化使用關鍵字static
進行修飾。例如:
void foo() {
static int count = 0; // 局部靜態變量
count++;
std::cout << "This function has been called " << count << " times." << std::endl;
}
int main() {
foo();
foo();
foo();
return 0;
}
輸出結果:
This function has been called 1 times.
This function has been called 2 times.
This function has been called 3 times.
在函數外部定義的靜態變量,它在程序啟動時被初始化,只初始化一次。全局靜態變量的初始化不需要使用關鍵字static
進行修飾。例如:
int global_count = 0; // 全局靜態變量
void foo() {
global_count++;
std::cout << "This function has been called " << global_count << " times." << std::endl;
}
int main() {
foo();
foo();
foo();
return 0;
}
輸出結果:
This function has been called 1 times.
This function has been called 2 times.
This function has been called 3 times.
注意:局部靜態變量和全局靜態變量的初始化順序在不同的編譯單元中是未定義的,但在同一編譯單元中的初始化順序是確定的。如果需要在不同編譯單元之間進行同步初始化,可以使用互斥鎖(mutex)等同步機制。