C++ 中的 static 关键字用于修改变量、函数和类成员,指示编译器保留其作用域和存储持续时间。其用法包括:声明 static 变量以保留函数调用或对象销毁后的值。声明 static 成员变量以在类的不同实例之间共享数据。使用 static 函数提供类级功能,而无需创建类的实例。static 关键字的优点包括提高效率、增强可测试性,以及在需要保留状态、共享数据或提供类级功能时很有用。

C++ 中 static 的用法和作用
是什么
static 是 C++ 中的一个关键字,用于修饰变量、函数和类成员。它指示编译器在程序的整个生命周期内保留其作用域、存储持续时间和链接属性。
用法
立即学习“C++免费学习笔记(深入)”;
变量
<code class="cpp">int main() {
static int x = 10; // 保留函数调用之间的值
return 0;
}</code>函数
<code class="cpp">class MyClass {
public:
static int add(int a, int b) {
return a + b;
}
};
int main() {
MyClass::add(1, 2); // 直接调用 static 函数
return 0;
}</code>类成员
<code class="cpp">class MyClass {
public:
static int count = 0; // 静态类变量
static void increment() {
count++;
}
};
int main() {
MyClass::increment(); // 通过类名访问 static 函数
cout << MyClass::count << endl; // 访问 static 变量
return 0;
}</code>作用
static 关键字在以下场景中很有用:
以上就是c++++中static的用法和作用的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号