1.首先创建一个类的头文件,便于以后对类的使用。包含类的成员变量和成员函数。stu.h
#ifndef _STU_H_
#define _STU_H_
class Student
{
char m_name[20];
int m_age;
Student *m_next;
public:
Student();
Student(char *name,int age);
void SetNext(Student *n);
Student *GetNext();
char *GetName();
int GetAge();
};
class Manage
{
Student *m_first;
int m_sum;
public:
Manage();
void Init();
void Insert();
void Show();
void List();
void Delete();
};
#endif
2.创建另一个文件,用于编写类中的成员函数。stu.cpp
#include "stu.h"
#include <cstring>
#include <iostream>
#include <cstdlib>
using namespace std;
Student::Student()
{
m_age = 0;
}
Student::Student(char *name,int age)
{
strcpy(m_name,name);
m_age = age;
}
void Student::SetNext(Student *n)
{
m_next = n;
}
Student *Student::GetNext()
{
return m_next;
}
char *Student::GetName()
{
return m_name;
}
int Student::GetAge()
{
return m_age;
}
Manage::Manage()
{
m_first = NULL; //带头结点的链表
m_sum = 0; //标记结点
}
void Manage::Init()
{
m_first = new Student;
}
void Manage::Show()
{
cout << "1.Insert 2.List" << endl;
cout << "3.Delete 4.exit" << endl;
}
void Manage::Insert()
{
char name[20];
int age;
Student *p = m_first;
cout << "Input name and age :" << endl;
cin >> name >> age;
Student *s = new Student(name,age);
for(int i = 0;i < m_sum;i++)
{
p = p -> GetNext(); //p指向最后一个结点的头
}
p -> SetNext(s); //最后一个结点的尾接上新结点s
m_sum++;
}
void Manage::List()
{
Student *p = m_first -> GetNext(); //指向头结点的下一个结点的头
for(int i = 0;i < m_sum;i++)
{
cout << p -> GetName() << " " << p -> GetAge() << endl;
p = p -> GetNext();
}
}
3.最后创建main函数文件,只需要调用其他文件中的函数,简洁明了。main.cpp
#include "stu.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char **argv)
{
int choice;
Manage M;
M.Init();
while(1)
{
M.Show();
cin >> choice;
switch(choice)
{
case 1 : M.Insert(); break;
case 2 : M.List() ; break;
//case 3 : M_delete(); break;
case 4 : exit(1) ; break;
}
}
return 0;
}