在C++中,static關鍵字可以用于標記變量或函數,它具有以下幾種內存分配機制:
void foo() {
static int count = 0;
count++;
cout << "count: " << count << endl;
}
int main() {
foo(); // count: 1
foo(); // count: 2
return 0;
}
static int globalVar = 10;
void foo() {
cout << "globalVar: " << globalVar << endl;
}
int main() {
foo(); // globalVar: 10
return 0;
}
class MyClass {
public:
static int count;
};
int MyClass::count = 0;
int main() {
MyClass obj1;
MyClass obj2;
cout << "obj1 count: " << obj1.count << endl; // obj1 count: 0
cout << "obj2 count: " << obj2.count << endl; // obj2 count: 0
MyClass::count = 10;
cout << "obj1 count: " << obj1.count << endl; // obj1 count: 10
cout << "obj2 count: " << obj2.count << endl; // obj2 count: 10
return 0;
}
總結來說,static關鍵字可以用于實現在程序運行期間只分配一次內存空間的變量或函數,并且具有不同的作用域和生命周期規則,可以提高程序的效率和靈活性。