在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关键字可以用于实现在程序运行期间只分配一次内存空间的变量或函数,并且具有不同的作用域和生命周期规则,可以提高程序的效率和灵活性。