12、static关键字

发布时间 2023-03-22 21:08:56作者: 摩天仑

static关键字可以修饰变量或者函数。

  1. 声明局部静态变量
  2. 声明类内静态数据成员/成员函数。

1、声明局部静态变量

void test()
{
  static int a = 1; // 静态局部变量
  int b = 1; // 普通局部变量
}
  1. 静态局部变量在函数内定义,但不像自动变量那样当函数被调用时就存在,调用结束就消失,静态变量的生存期为整个源程序。
  2. 静态变量的生存期虽然为整个源程序,但是作用域与自动变量相同,即只能在定义该变量的函数内使用该变量,退出函数后虽然变量还存在,但不能够使用它
    image
  3. 对基本类型的静态局部变量如果在声明时未赋初始值,则系统自动赋0值;而对普通局部变量不赋初始值,那么它的值是不确定的
    image

声明类内静态数据成员/成员函数

  1. 不用实例化对象就可以直接使用。
  2. 当不同对象有相同的属性就可以使用。比如我们都是人,但是我们看到的当前时间都是一致,可以设置为static。

2.1 非const静态成员变量

必须在类外初始化,在类内初始化失败

#include <iostream>
using namespace std;

class Test
{
public:
  static int a;
  int b = 2;
};
int Test::a = 1;

int main() {
  cout << Test::a <<endl;
  system("pause");
  return 0;
}

image

2.2 const 静态成员变量

在类内和类外均可初始化

#include <iostream>
using namespace std;

class Test
{
public:
  // static int a;
  static const int b = 1;
  static const int c;
  int d = 2;
};
const int Test::c = 1;

int main() {
  cout << "Test::b = " << Test::b <<endl;
  cout << "Test::c = " << Test::c <<endl;
  system("pause");
  return 0;
}

image

2.3 静态成员函数

  1. 静态成员函数可在类内和类外初始化;
  2. 静态函数只能访问静态成员变量,普通成员函数可以访问所有成员;
#include <iostream>
using namespace std;

class Test
{
public:
  static const int a = 1; 
  static void test(){
    // 写法1
    cout << "我是test " << "a=" << a <<endl;
    // 写法2
    cout << "我是test " << "Test::a=" << Test::a <<endl;
  }
};

int main() {
  Test::test();
  system("pause");
  return 0;
}

image

静态函数访问普通成员报错
image