C++类中的static成员函数和static数据成员

1、static数据成员的使用

1.1 static数据成员的定义

static数据成员可以声明为任意类型,可以是常量、引用、数组、类类型。static数据成员在类内声明,但是必须在类定义体的外部定义,也就是必须在类外进行定义。在使用类内的static成员时,和其他的成员变量的使用方法相同。

class ChineseClass
{
public:
	void Note();
	ChineseClass(string &address,int Nums)
	{
		this->studentNums=Nums;
		this->address=address;
	}
	static void classInfor();
private:
	int studentNums;
	string address;
	static int lessonNums;
	
};
int ChineseClass::lessonNums=40;//在进行定义的时候不用加上static关键。类名::变量名=值

以下是源文件代码:

void ChineseClass::Note()
{
	cout<<"room number is"<<this->address<<endl;
	cout<<"there are"<<this->studentNums<<endl;
	
}
void ChineseClass::classInfor()
{
	cout<<"there are"<<" "<<lessonNums<<" "<<"lessons"<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	string add="305";
	ChineseClass chineseclass(add,35);
	chineseclass.Note();
	chineseclass.classInfor();
	return 0;
}

1.2 特殊的static成员声明和定义

前面说过static数据成员可以在类内进行声明,但是只能在类外进行定义。static成员不可以使用构造函数来进行初始化。但是特殊的static const int类型的数据成员是可以在类内进行声明和初始化的。其他的const string,const double等,都不可以在类内进行定义。


1.3 static成员不是类对象的组成部分

static是类的组成部分,但是类实例化为对象后,该类的static成员却和该对象没有联系,不是该对象的组成部分。static数据成员可以声明为该类类型的成员变量,而非static成员只能被限定为其自身类对象的指针或引用。

class ChineseClass
{
public:
	void Note();
	ChineseClass(string &address,int Nums)
	{
		this->studentNums=Nums;
		this->address=address;
	}
	static void classInfor();
private:
	int studentNums;
	string address;
	static int lessonNums;
	static ChineseClass wonderfulClass;
	ChineseClass *goodClass;

也就是说如果你声明的这个类中想要使用自身这个类,那么你要么把这个类定义为static,要么把这个类定为这个类的指针或者是引用。而你如果直接写成ChineseClass  goodClass,那么这个声明是错误的,编译器无法通过的。

2、static成员函数

2.1 static没有this指针

这点是最重要的!!static成员函数的的确确是类的组成部分,但是却不是任何对象的组成部分。因此,static成员函数是没有this指针的。同时static成员函数不能被声明为const函数。并且static成员函数也不能被声明为虚函数。它可以直接访问多数类的static成员,但是不能使用非static成员。

void ChineseClass::classInfor()
{
	cout<<"there are"<<" "<<lessonNums<<" "<<"lessons"<<endl;
}
之前我将classInfor()函数声明为static,所以可以直接在类定义域内直接使用static数据成员,但是无法使用非static数据成员。



  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值