首先,我们可以先看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、静态成员变量在使用之前,需要在类的外面对其进行初始化。