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变量作用域取决于它的定义位置。在函数内部定义的静态变量仅在该函数中可见,而在全局作用域或类中定义的静态变量在整个程序中可见。