demo_3_static_member_6.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 59 行

CPP
59
字号

//************************************************
//由学生类组成的单向链表中的静态成员

# include <iostream.h>
# include <string.h>

class Student
{
public:
	Student(char* pName);
	~Student() { cout<<"Destruct One Student : "<<name<<endl;	}
	static char* findname(char* pName);
protected:
	static Student* pFirst;
	Student* pNext;
	char name[40];
};

Student* Student::pFirst=NULL;

Student::Student(char* pName)
{
	cout<<"Construct One Student : "<<pName<<endl;

	strncpy(name,pName,sizeof(name));
	name[sizeof(name)-1]='\0';

	pNext=pFirst; //每新建一个节点(对象),就将其挂在链首
	pFirst=this;  //this指针是当前节点(对象)
}

char* Student::findname(char* pName)
{
	for(Student* pS=pFirst;pS;pS=pS->pNext)
	{
		if(strcmp(pS->name,pName)==0)
		{
			return pName;
		}
	}

	return NULL;
}

void main()
{
	Student s1("Randy");  
	Student s2("Jenny");  
	Student s3("Emme");  

	char* pName=Student::findname("Jenny");

	if(pName)
		cout<<pName<<endl;
	else
		cout<<"no find!"<<endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?