// static在C++语言中的用法
// 1. 静态局部变量
#include <iostream>
using namespace std;
void func() {
static int count = 0; // 静态局部变量,只初始化一次
count++;
cout << "count: " << count << endl;
}
int main() {
func(); // 输出 count: 1
func(); // 输出 count: 2
return 0;
}
// 2. 静态成员变量
class MyClass {
public:
static int value; // 声明静态成员变量
static void setValue(int v) {
value = v; // 可以在静态成员函数中访问静态成员变量
}
static int getValue() {
return value;
}
};
int MyClass::value = 0; // 定义并初始化静态成员变量
int main() {
MyClass::setValue(10);
cout << "MyClass::value: " << MyClass::getValue() << endl;
return 0;
}
// 3. 静态成员函数
class AnotherClass {
public:
static void staticFunc() {
cout << "This is a static member function." << endl;
}
};
int main() {
AnotherClass::staticFunc(); // 调用静态成员函数
return 0;
}
// 4. 静态全局变量
#include <iostream>
using namespace std;
static int globalVar = 100; // 静态全局变量,仅在本文件中可见
void printGlobalVar() {
cout << "globalVar: " << globalVar << endl;
}
int main() {
printGlobalVar();
return 0;
}
静态局部变量:static 关键字用于局部变量时,该变量的生命周期将扩展到整个程序运行期间,但作用域仍然限于定义它的函数内部。这意味着它只会被初始化一次,并且在函数调用之间保留其值。
静态成员变量:static 关键字用于类的成员变量时,该变量属于类本身而不是类的对象。所有对象共享同一个静态成员变量。静态成员变量需要在类外部进行定义和初始化。
静态成员函数:static 关键字用于类的成员函数时,该函数不依赖于任何特定的对象实例,因此不能访问非静态成员变量或调用非静态成员函数。静态成员函数可以通过类名直接调用。
静态全局变量:static 关键字用于全局变量时,该变量的作用域将被限制在定义它的文件内,其他文件无法访问该变量。
上一篇:c++注释
下一篇:c++重载
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站