C++学习笔记-类中的static

类和结构体中的static变量和文件中的static是一个道理,只不过是在类中私有的,外部无法找到,因此需要在外部定义这个变量,就和你extern是一个道理,只不过这个类是在你当前文件中的,因此不需要extern关键字。

Main.cpp

 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
struct Entity
{
	static int x, y;
	int z;

	static void Print()
	{
		std::cout << x << "," << y << std::endl;
		//std::cout << z << std::endl; // 静态函数不能引用非静态变量
	}
};

/*外部使用类中的静态变量,需要定义这些变量 */
int Entity::x;
int Entity::y;

int main()
{
	//Entity e1;
	//e1.x = 2;
	//e1.y = 3;
	//e1.Print(); // 2,3

	/* 静态变量不需要实例,因此引用直接用类名::变量名即可 */
	Entity::x = 2;
	Entity::y = 3;
	Entity::Print();
}

总结

  1. 类中的static变量被这个类的所有实例所共享。
  2. 访问类和结构体中的静态成员使用【类名/结构体名::变量名】来引用。
  3. 静态函数不能引用非静态变量,因为静态函数没有类的实例
  4. 在程序启动时初始化,程序结束时销毁(与全局变量生命周期相同)。
updatedupdated2025-03-102025-03-10