C++类的static
发表于:2024-12-08 | 分类: C++
字数统计: 876 | 阅读时长: 3分钟 | 阅读量:

类、static

静态成员变量

  • 需要在类外部初始化初始化后类才能访问它**,所有函数**都可以访问它
  • 静态变量所有对象共享,会保留上一次操作的值
  • 不占用对象的内存,而是在所有对象之外开辟内存,不随对象的创建销毁而创建销毁
  • 访问
    • 对象名访问
    • this访问
    • 类名::访问
  • 声明时要加 static,在定义时不能加 static
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
using namespace std;

class Student
{
public:
Student(char *name, int age);
void show();

private:
static int num; // 静态成员变量

private:
char *name;
int age;
};

// 初始化静态成员变量,通过类名在对象外部初始化,定义时不加static
int Student::num = 0;

Student::Student(char *name, int age)
{
// 每次创建对象,静态成员变量加1,也可以使用this
this->name = name;
this->age = age;
num++;
}
void Student::show()
{
cout << name << "的年龄是" << age << endl;
cout << "当前创建了" << num << "个对象" << endl;
}

int main()
{
// 创建匿名对象(无名字,只做演示,无法释放,会有内存泄露)
// num的变化是1,2,3
(new Student("java", 15))->show();
(new Student("python", 16))->show();
(new Student("c++", 16))->show();

return 0;
}

静态成员函数

  • 普通成员函数可以访问类的所有成员(包含静态成员)
  • 静态成员函数:没有this,只能访问类的静态成员(任何权限的都可以)
  • 声明时要加 static,在定义时不加 static
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;

class Student
{
public:
Student(char *name, int age);
void show();

public:
// 声明静态成员函数
static int getnum();
static void showNum();

private:
// 静态变量总人数
static int num;

private:
char *name;
int age;
};

// 初始化静态变量
int Student::num = 0;

Student::Student(char *name, int age)
{
this->name = name;
this->age = age;
num++;
}

void Student::show()
{
cout << name << "," << age << endl;
cout << "num:" << num << endl; // 普通成员函数可以访问静态变量
getnum(); // 普通成员函数可以访问静态成员函数
}

// 定义静态成员函数,定义时不加static
int Student::getnum()
{
return num;
}

void Student::showNum()
{
// cout << age << endl; 报错,只能调用静态成员
// show();报错,只能调用静态成员
getnum(); // 正确,getnum()是静态成员函数,可以调用静态成员变量
cout << "num:" << num << endl; // 正确,num是静态成员变量,可以调用静态成员函数
}

int main()
{
(new Student("java", 15))->show();
(new Student("python", 16))->show();
(new Student("c++", 16))->show();

Student::showNum();
return 0;
}

静态局部和全局变量

特性 局部静态变量 全局变量
作用域 函数或代码块内 整个程序或受限于文件(静态全局变量)
生命周期 整个程序运行期 整个程序运行期
可见性 局部 全局或文件内部(静态全局变量)
初始值 默认初始化为 0 默认初始化为 0
存储位置 静态存储区 静态存储区
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>

// 静态全局变量,仅当前文件可见
static int staticGlobal = 100;

// 普通全局变量
int globalVar = 50;

void testStaticLocal()
{
static int localStatic = 10; // 静态局部变量
localStatic++;
printf("Local Static: %d\n", localStatic);
}

void testGlobal()
{
staticGlobal++;
globalVar++;
printf("Static Global: %d, Global Var: %d\n", staticGlobal, globalVar);
}

int main()
{
testStaticLocal(); // 11
testStaticLocal(); // 12

testGlobal(); // 51
testGlobal(); // 52

return 0;
}
上一篇:
字符串
下一篇:
C++类