C++ 静态成员函数小练习

首先,我们可以先看1个小例子:

/*
建立一个学生类,每个学生类的对象将组成一个双向链表,
用一个静态成员变量记录这个双向链表的表头,
一个静态成员函数输出这个双向链表。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
const int MaxNameLength=100;
class Student
{
public:
	Student(char name[]);
	~Student();
public:
	static void PrintAllStu();
private:
	Student *prev;
	Student *next;
	static Student *m_head;
	static int num;
	char name[MaxNameLength];
};
Student::Student(char in_name[])
{
	this->prev = m_head;
	this->next = NULL;
	strcpy_s(this->name,in_name);
	if(m_head==NULL)
		m_head = this;
	m_head = this;
	num++;
}
Student::~Student()
{
	if(this == m_head)
		this->next = NULL;
	else
	{
		if(this->next)
		{
			this->next->prev = this->prev;
			this->prev->next = this->next;
		}
		else
		{
			if(this->prev)
				this->prev->next = NULL;
		}
		
	}
}
void Student::PrintAllStu()
{
	printf("Here we have %d sutdents:\n",num);
	Student *p = m_head;
	while(p)
	{
		printf("%s ",p->name);
		p = p->prev;
	}
	//printf("%d ",num);
	
}
Student * Student::m_head = NULL;
int Student::num = 0;
int main()
{	
	Student stu1("abc");
	Student stu2("123");
	Student stu3("hello");
	Student :: PrintAllStu();
	system("PAUSE");
	return 0;
}


通过这个小例子,我们需要注意到3点:

1、静态成员函数不能调用非静态成员;

2、非静态成员函数可以调用静态成员,静态成员属于类本身,在类的对象产生之前就已经存在了,另外需要注意的是,在类的外面是不可以访问它的静态成员变量的;

3、静态成员变量在使用之前,需要在类的外面对其进行初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值