C++:类的静态成员变量、静态成员常量、静态成员函数

静态成员使用遵循以下几点:

  1. 静态成员变量不能通过参数列表来初始化,只能在类外初始化(int ClsTest::total = 0;),如果不初始化则为编译器默认值;
  2. 静态成员常量可以在类内定义时直接初始化也可以像静态成员变量一样类内声明,类外定义;
  3. 静态成员是属于类而不是属于对象,不占用对象的空间,但对象可以引用它,不需要使用特殊的格式,是所有对象共有,一旦改变,各对象都跟着改变
  4. static成员依然保持public,private,protected访问准则;
#include <iostream>

using namespace  std;

class ClsTest
{
public:
	static int total;
private: 
	static const int rate = 100;	// 静态成员常量可以直接初始化,static const 等于 const static
};

int ClsTest::total = 0;				// 必须在外部初始化,且不需要加static 
// const int ClsTest::rate = 100;	// 静态常量也可以在外部初始化 

int main()
{
	ClsTest t1, t2;
	
	t1.total = 100;
	cout << "Total 1: " << t2.total << endl;
	cout << "Total 2: " << ClsTest::total << endl; 	// 各个对象都跟着变化,这2种方式都可以访问 
	//cout << "Rate: " << ClsTest::rate << endl;	// 不能访问私有 
	
	return 0;
}

/*
输出结果:
Total 1: 100
Total 2: 100
*/
  1. 普通成员函数可以引用所有的成员(不管是否为静态),而静态成员函数只能使用静态成员而不能访问其他非静态成员
#include <iostream>

using namespace  std;

class ClsTest
{
public:
	static void s_func(){
		s_test();
		//test();	// 不可以引用非静态成员(包括函数和变量) 
	}
	void func(){
		s_test();
		test();
	}
private:
	static void s_test(){
		cout << "s_test" << endl;
	}
	void test(){
		cout << "test" << endl;
	}
};

int main()
{
	ClsTest t1;

	t1.s_func();
	t1.func();
	
	return 0;
}
/*
输出结果:
s_test
s_test
test
*/
  1. 子类继承之后依然保持着静态变量,不需要重复初始化
#include <iostream>

using namespace  std;


/* 类ClsTest */ 
class ClsTest
{
public:
	static int total;
};
int ClsTest::total = 0;


/* 类ClsTest2继承ClsTest */ 
class ClsTest2 : public ClsTest
{

};
// int ClsTest2::total = 0;			// 错误,已经在ClsTest定义初始化,无须重复 


int main()
{
	ClsTest t1;
	
	t1.total = 100; 	
	cout << "Total 1: " << ClsTest::total << endl;

	ClsTest2 t2;
	cout << "Total 2: " << t2.total << endl;
	cout << "Total 3: " << ClsTest2::total << endl; // 子类保持着静态成员的值 
	
	return 0;
}
/*
输出结果:
Total 1: 100
Total 2: 100
Total 3: 100
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R-QWERT

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值