静态成员

#include <iostream>
#include <string.h>
using namespace std;

class Student
{
public:
	Student(char *pName = "No name")
	{
		cout<<"create one student\n";
		strcpy(name,pName);
		cout<<name<<endl;
		noOfStudent++;//静态成员:每创建一个对象,学生人数+1
		cout<<noOfStudent<<endl<<endl;
		pNext = pFirst;//每创建一个节点(对象),就把他挂在链首
		pFirst = this;
	}
	~Student()
	{
		cout<<"destruct one student\n";
		cout<<name<<endl;
		noOfStudent--;//每析构一个对象,学生人数-1
		cout<<noOfStudent<<endl<<endl;
		if (pFirst == this)
		{
			//如果要删除链表结点,则只要链首指针指向下一个
			pFirst = this->pNext;
			return;
		}
		for (Student *pS = pFirst; pS; pS = pS->pNext)
		{
			if (pS->pNext == this)
			{
				//找到时,pS指向当前结点
				pS->pNext = this->pNext;
				return ;
			}
		}
	}
	//静态成员函数
	static int number()
	{
		return noOfStudent;
	}
	static Student* FindName(char *pName)
	{
		for (Student *pS = pFirst; pS; pS = pS->pNext)
		{
			if (strcmp(pS->name,pName) == 0)
			{
				return pS;
			}
		}
		return (Student*)0;//返回空指针
	}
protected:
	static int noOfStudent;
	static Student *pFirst;
	Student *pNext;
	char name[40];
};

//类声明只声明一个类的"尺寸与规格",并不进行实际的内存分配
//静态数据成员在类声明外分配空间和初始化
int Student::noOfStudent = 0;
Student* Student::pFirst = 0;

void fn()
{
	Student s1;
	Student s2;
	cout<<Student::number()<<endl;//调用静态成员函数用类名引导
}

Student* fn2()
{
	Student *pS = new Student("Jenny");
	Student sb("Jone");
	return pS;
}



int main()
{
	/*fn();
	cout<<Student::number()<<endl;*/

	/*Student sa("Jamsa");
	Student *sb = fn2();
	Student sc("Tracy");
	delete sb;*/

	Student s1("Randy");
	Student s2("Jenny");
	Student s3("Kinsey");
	Student *pS = Student::FindName("Jenny");
	if (pS)
		cout<<"ok."<<endl;
	else
		cout<<"no find."<<endl;
	return 0;
}
posted @ 2010-10-12 20:54  Cranny  阅读(255)  评论(0编辑  收藏  举报