C++中static成员变量

1)static成员变量属于类,不属于某个具体的对象,即使创建多个对象,也只为static成员变量分配一个内存

     所有对象都是这个内存里的statiic变量,如果对其做出修改也会影响到其他对象的使用

2)static成员变量必须在类外进行初始化

形如  type class ::name = value;    int Parent ::count = 0;

class Parent
{
public:
	int age;
	int score;
	static int count;

	Parent(int age, int score);

	void Show()
	{
		cout << age << " " << score << endl;
		cout << count << endl;
	}
};

int Parent :: count = 0;    ///在类外初始化

Parent ::Parent(int age, int score)
{
	this->age = age;
	this->score = score;
	count++;
}

int main()
{
	Parent P(2, 3);
	P.Show();

	Parent p(3, 4);
	p.Show();

	while(1);

	return 0;
}

3)static成员变量不占用对象内存,是在对象之外(全局数据区)开辟一块内存,即使不创建对象也不能访问。

 4)static成员变量不随对象的创建而创建,不随对象的销毁而销毁,在程序结束时在销毁;普通成员变量随对象创建,随对象销毁

class Parent
{
public:
	int age;
	int score;
	static int count;

	Parent(int age, int score);

	void Show()
	{
		cout << age << " " << score << endl;
		cout << count << endl;
	}
};

int Parent :: count = 0;

Parent ::Parent(int age, int score)
{
	this->age = age;
	this->score = score;
	count++;
}

int main()
{
	cout << Parent :: count << endl;        //未创建对象,一样访问,打印出来值为0

	while(1);

	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值