static
关键字在C++中有多种用途,取决于它的使用位置。它可以用于变量、函数和成员函数。以下是不同上下文中的详细说明:
1. 静态全局变量和静态函数
- 作用域:文件范围
- 说明:当
static
用于全局变量或函数时,该变量或函数的作用域限制在定义它的文件中。
// file1.cpp
static int globalVar = 10;
static void staticFunction() {
std::cout << "This is a static function." << std::endl;
}
void nonStaticFunction() {
std::cout << "This is a non-static function." << std::endl;
}
// file2.cpp
extern int globalVar; // Error: globalVar is not visible here
void callStaticFunction() {
staticFunction(); // Error: staticFunction is not visible here
}
2. 静态局部变量
- 作用域:块范围(局部)
- 生命周期:程序生命周期
- 说明:当
static
用于函数内部的局部变量时,该变量在函数的多次调用之间保持其值。
void counter() {
static int count = 0;
++count;
std::cout << "Count: " << count << std::endl;
}
int main() {
counter(); // Output: Count: 1
counter(); // Output: Count: 2
return 0;
}
3. 静态成员变量
- 作用域:类范围
- 生命周期:程序生命周期
- 说明:当
static
用于类的成员变量时,该变量在所有对象间共享,且该变量不属于某个具体的对象,而是属于类。
class MyClass {
public:
static int staticVar;
static void staticMethod() {
std::cout << "Static variable: " << staticVar << std::endl;
}
};
int MyClass::staticVar = 0;
int main() {
MyClass::staticVar = 5;
MyClass::staticMethod(); // Output: Static variable: 5
return 0;
}
4. 静态成员函数
- 作用域:类范围
- 说明:当
static
用于类的成员函数时,该函数可以在不创建对象的情况下调用,且不能访问非静态成员变量。
class MyClass {
public:
static void staticMethod() {
std::cout << "This is a static method." << std::endl;
}
};
int main() {
MyClass::staticMethod(); // Output: This is a static method.
return 0;
}
总结
- 静态全局变量和静态函数:作用域限制在定义它们的文件内,其他文件不可见。
- 静态局部变量:在函数内部声明,函数多次调用间保持值。
- 静态成员变量:属于类而非具体对象,所有对象间共享。
- 静态成员函数:可以在不创建对象的情况下调用,不能访问非静态成员。