C++中的static變量具有以下作用域:
void func() {
static int count = 0;
count++;
cout << "This function has been called " << count << " times." << endl;
}
int global_count = 0;
void func() {
static int count = 0;
count++;
cout << "This function has been called " << count << " times." << endl;
}
class MyClass {
public:
static int count;
};
int MyClass::count = 0;
void func() {
MyClass obj;
MyClass::count++;
cout << "MyClass has been instantiated " << MyClass::count << " times." << endl;
}
總之,C++中的static變量作用域取決于它的定義位置。在函數內部定義的靜態變量僅在該函數中可見,而在全局作用域或類中定義的靜態變量在整個程序中可見。