C ++中的静态关键字

使用static关键字时,不能再次修改变量或数据成员或函数。它在程序的生命周期内分配。静态函数可以通过使用类名直接调用。

静态变量仅初始化一次。编译器将变量保留到程序结束。静态变量可以在函数内部或外部定义。它们在块本地。静态变量的默认值为零。静态变量在程序执行之前一直有效。

这是C ++语言中static关键字的语法,

static datatype variable_name = value;      // Static variable
static return_type function_name {             // Static functions
   ...
}

这里,

datatype-变量的数据类型,例如int,char,float等。

variable_name-这是用户给定的变量名。

-来初始化变量的任何值。默认情况下,它为零。

return_type-返回值的函数的数据类型。

function_name-函数的任何名称。

这是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 b;
Base::func(8);
cout << "\nThe static variable value : " << b.val;