在 C++ 中,关键字 static
有几种不同的用途,主要用于管理存储类和访问类的范围。下面详细介绍 static
的每个用法,并提供相应的代码示例、代码解释以及运行结果。
C++ static的所有用法及对应的代码示例
1. 局部静态变量
当 static
用于函数内的局部变量时,它会使变量保持其值状态,即使在函数调用结束后也不会销毁。这样的变量只初始化一次,每次函数调用时保留其最后一次使用的值。
代码示例:
#include <iostream>
using namespace std;
void countFunction() {
static int count = 0;
count++;
cout << "Count: " << count << endl;
}
int main() {
countFunction(); // 输出 1
countFunction(); // 输出 2
countFunction(); // 输出 3
return 0;
}
运行结果:
Count: 1
Count: 2
Count: 3
2. 全局静态变量
在函数外部使用 static
声明的全局变量或函数,限制了其链接性(可见性),使其只在定义它的文件中可见。
代码示例:
// file1.cpp
#include <iostream>
static int globalValue = 10;
void display() {
std::cout << "Global Value in file1: " << globalValue << std::endl;
}
// file2.cpp
#include <iostream>
extern int globalValue; // 编译错误,globalValue 在 file2 中不可见
int main() {
display();
}
运行结果:
Global Value in file1: 10
(注意:这里的 “file2.cpp” 编译时将会报错,因为 globalValue
对它不可见)
3. 静态类成员变量
static
也可以用于类的成员变量。这种情况下,变量不属于任何特定的对象实例,而是类的所有实例共享的。它们必须在类外部初始化。
代码示例:
#include <iostream>
using namespace std;
class MyClass {
public:
static int staticValue;
};
int MyClass::staticValue = 0;
int main() {
MyClass::staticValue = 5;
cout << "Static Value: " << MyClass::staticValue << endl; // 输出 5
MyClass obj1, obj2;
obj1.staticValue = 2;
cout << "Static Value from obj2: " << obj2.staticValue << endl; // 输出 2
return 0;
}
运行结果:
Static Value: 5
Static Value from obj2: 2
4. 静态类成员函数
类方法也可以声明为 static
。这样的方法可以在没有任何对象实例的情况下调用,并且只能访问其类的静态成员。
代码示例:
#include <iostream>
using namespace std;
class MyClass {
public:
static int staticValue;
static void displayValue() {
cout << "Static Value: " << staticValue << endl;
}
};
int MyClass::staticValue = 10;
int main() {
MyClass::displayValue(); // 输出 10
return 0;
}
运行结果:
Static Value: 10
这些例子涵盖了 static
在 C++ 中的主要用法,有助于理解如何在不同情景中使用它以及其对程序行为的影响。