C++中静态方法在类和结构体内

C++中静态方法在类和结构体内 Static for Classes and Structs in c++


视频教程:youtube 原链接:https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb


今天我们来讨龙在class或者struct内部的static是什么意思。
在几乎所有面向对象的语言中。class内部的static代表一个特定的东西。假设你在一个class中创建一个static变量。那么在这个类的所有实例中,这个static变量都只有这一个。也就是说,如果其中一个实例改变了这个static变量,那么所有实例中的static变量都会随之改变。
因此,通过类实例来引用静态变量是没有意义的。静态方法不能访问类的实例,不通过类的实例就可以直接调用静态方法。
下面是结构体里设置普通变量的例子:

#include <iostream>

struct Entity
{
	int x, y;

	void Print()
	{
		std::cout << x << "," << y << std::endl;
	}
};

int main()
{
	Entity e;
	e.x = 2;
	e.y = 2;

	Entity e1 = {5, 8};

	e.Print();
	e1.Print();

	std::cin.get();
}

输出为

2,2
5,8  

如果把变量改为静态的
Entity e1 = {5, 8};这种写法会报错,因为x,y不再是类的成员。

#include <iostream>

struct Entity
{
	static int x, y;

	void Print()
	{
		std::cout << x << "," << y << std::endl;
	}
};

int Entity::x;
int Entity::y;

int main()
{
	Entity e;
	e.x = 2;
	e.y = 2;

	Entity e1;
	e1.x = 5;
	e1.y = 8;

	e.Print();
	e1.Print();

	std::cin.get();
}

在我们引用静态变量时,首先要定义它的值。
输出如下

5,8
5,8

静态变量指向同一个内存空间,因此后面值发生改变时前面的也会跟着改变。
e1.x = 5;
e1.y = 8;
这样引用变量也没有意义
Entity::x = 5;
Entity::y = 8;
这样引用。但你打算跨类去使用变量时,就可以用上静态方法,你可以只建一个全局变量或者用一个静态全局变量来代替全局变量。静态全局变量会在单元内部进行连接而不会在整个项中全局可见,就像上述 static int x, y; 。

那静态变量放在class中的意义是什么呢?
如上述,类中的静态变量在所有实例中共享。如果你有一条信息需要这样,并且它和这个类相关,那么你就可以用在类中创建静态变量的方法。

#include <iostream>

struct Entity
{
	static int x, y;

	static void Print()
	{
		std::cout << x << "," << y << std::endl;
	}
};

int Entity::x;
int Entity::y;

int main()
{
	Entity e;
	Entity::x = 2;
	Entity::y = 2;

	Entity e1;
	Entity::x = 5;
	Entity::y = 8;

	Entity::Print();
	Entity::Print();

	std::cin.get();
}  

静态方法可以访问静态变量;静态方法不能访问非静态变量;
说实话,我有点不明所以,不过没关系,代码行不行,运行一下就知道了,实践类的东西就是这么直接明了
想下面这样就会报错

struct Entity
{
	int x, y;

	static void Print()
	{
		std::cout << x << "," << y << std::endl;
	}
};


int main()
{
	Entity e;
	e.x = 2;
	e.y = 2;

	Entity e1;
	e1.x = 5;
	e1.y = 8;

	Entity::Print();
	Entity::Print();

	std::cin.get();
}

报错: “非静态成员引用必须与特定对象相对”。静态实例在类内就像在外面一样,它不知道类内的x,y是什么。因此下面我们给它一个类的引用,程序就可以正确运行。
下面是正确引用

#include <iostream>

struct Entity
{
	int x, y;

	static void Print(Entity e)
	{
		std::cout << e.x << "," << e.y << std::endl;
	}
};


int main()
{
	Entity e;
	e.x = 2;
	e.y = 2;

	Entity e1;
	e1.x = 5;
	e1.y = 8;

	Entity::Print(e);
	Entity::Print(e1);

	std::cin.get();
}

输出为:

2,2
5,8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值