C++ 中的 static 关键字
当使用 static 关键字时,变量、数据成员或函数将无法再次修改。它被分配到程序的整个生命周期。静态函数可以直接使用类名调用。
静态变量只初始化一次。编译器会将变量保持到程序结束。静态变量可以在函数内部或外部定义。它们对于该块是局部的。静态变量的默认值为零。静态变量在程序执行期间一直存在。
以下是 C++ 语言中 static 关键字的语法:
static datatype variable_name = value; // Static variable
static return_type function_name { // Static functions
...
}
这里:
数据类型 - 变量的数据类型,例如 int、char、float 等。
变量名 - 这是用户提供的变量名。
值 - 用于初始化变量的任何值。默认为零。
返回类型 - 函数返回的值的数据类型。
函数名 - 函数的任何名称。
以下是一个 C++ 语言中静态变量的示例:
示例
#include <bits/stdc++.h>
using namespace std;
class Base {
public : static int val;
static int func(int a) {
cout << "\nStatic member function called";
cout << "\nThe value of a : " << a;
}
};
int Base::val=28;
int main() {
Base b;
Base::func(8);
cout << "\nThe static variable value : " << b.val;
return 0;
}
输出
Static member function called The value of a : 8 The static variable value : 28
在上面的程序中,一个静态变量被声明,一个静态函数在类 Base 中定义,如下所示:
public : static int val;
static int func(int a) {
cout << "\nStatic member function called";
cout << "\nThe value of a : " << a;
}
在类和 main() 之前,静态变量初始化如下:
int Base::val=28;
在函数 main() 中,创建 Base 类的对象并调用静态变量。静态函数也无需使用 Base 类的对象即可调用,如下所示:
Base b; Base::func(8); cout << "\nThe static variable value : " << b.val;
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP