学生入校离校统计
#include <iostream>
using namespace std;
class Student
{
public:
Student(char* pName);//构造函数
~Student();//析构函数
static Student* findname(char* pName);//静态成员函数,查找链中所有对象,查看有没有指定学生,返回Student类指针
static int getallStudent();
char* getName();
protected:
private:
static Student* head;
Student* next;
static int allStudent;
char name[40];
};
Student* Student::head = 0;
int Student::allStudent = 0;
int Student::getallStudent()
{
return allStudent;
}
char* Student::getName()
{
return name;
}
Student::Student(char* pName)
{
strcpy(name,pName);
name[sizeof(name)-1] = '\0';
next = head;
allStudent++;
head = this;//新创建的对象变成链表头
cout<<name<<"入学。"<<endl;
}
Student::~Student()
{
if (head == this)//链表头是要删除的对象吗
{
head = next;//链表头是要删除的对象
cout<<name<<"离校。"<<endl;
allStudent--;
return;
}
for (Student* p = head;p;p = p->next)//链表头不是要查找的对象,逐个查找。
{
if (p->next == this)//找到要删除的对象
{
p->next = next;
cout<<name<<"离校。"<<endl;
next = head;
allStudent--;
return;
}
}
allStudent--;
cout<<allStudent<<"离校。"<<endl;
}
Student* Student::findname(char* pName)
{
for (Student* p = head;p;p = p->next)
{
if (strcmp(p->name,pName) == 0)
return p;
}
return NULL;
}
int main()
{
Student* p = new Student("Randy");
cout<<"共有"<<p->getallStudent()<<"个对象。"<<endl;
Student* p1 = new Student("Jean");
cout<<"共有"<<p1->getallStudent()<<"个对象。"<<endl;
Student* p2 = new Student("Kinsey");
cout<<"共有"<<p2->getallStudent()<<"个对象。"<<endl;
delete p;
Student* p3 = new Student("Rose");
cout<<"共有"<<p3->getallStudent()<<"个对象。"<<endl;
Student* p4 = new Student("John");
cout<<"共有"<<p4->getallStudent()<<"个对象。"<<endl;
Student* f = Student::findname("Rose");
if (f)
cout<<f->getName()<<"找到了。"<<endl;
else
cout<<"未找到。"<<endl;
system("pause");
return 0;
}
结果显示: