用模板写通用链表方法之一
以前老师要我们用C语言写通用链表,由于是通用嘛,数据的输入输出就不一样,所以得链表算法和数据分离开来.最近学了多态,可以用基类指针指向派生类的方式写通用链表,实现起来更加方便.今天又给我们讲了一个另类的模板的方法.
// ListTtest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Student.h"
//模板不能分多文件写
template
class CList
{
class CNode
{
public:
T m_Data;
CNode *m_pLast;
CNode *m_pNext;
};
public:
CList();
~CList();
T* Create();
T* Add();
void ClearList();
private:
CNode *m_pHead;
CNode *m_pLast;
};
template
CList
::CList()
{
m_pHead = NULL;
m_pLast = NULL;
}
template
CList
::~CList() { ClearList(); } template
T* CList
::Create() { if(NULL != m_pHead) { return NULL; } m_pHead = new CNode; if(NULL == m_pHead) { return NULL; } m_pHead->m_pNext = NULL; m_pHead->m_pLast = NULL; m_pLast = m_pHead; return &(m_pHead->m_Data); } template
T* CList
::Add() { if(NULL == m_pHead) { return NULL; } CNode *pNew = new CNode; pNew->m_pLast = m_pLast; pNew->m_pNext = NULL; m_pLast = pNew; return &(pNew->m_Data); } template
void CList
::ClearList() { CNode *pTemp = m_pHead; while(NULL != pTemp) { m_pHead = m_pHead->m_pNext; delete pTemp; pTemp = m_pHead; } } int main(int argc, char* argv[]) { //CList
*pObj; 定义为指针时,由于没有分配空间,所以调用Create函数的时候会崩溃;可以这么写 //(pObj->Create())->Input(); CList
*pObj = new CList
; (pObj->Create())->Input(); CList
Obj; Obj.Create()->Input(); return 0; }
// Student.cpp: implementation of the CStudent class.
//
//
#include "stdafx.h"
#include "Student.h"
//
// Construction/Destruction
//
CStudent::CStudent()
{
m_szNum[0] = ' ';
m_nAge = 0;
}
CStudent::~CStudent()
{
}
void CStudent::Input()
{
cout<<"Please input student number:";
cin>>m_szNum;
cout<<"Please input student age:";
cin>>m_nAge;
}
// Student.h: interface for the CStudent class.
//
//
#if !defined(AFX_STUDENT_H__E0DF041B_A9A3_46F4_B7E0_1CAA9AF3D392__INCLUDED_)
#define AFX_STUDENT_H__E0DF041B_A9A3_46F4_B7E0_1CAA9AF3D392__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CStudent
{
public:
CStudent();
~CStudent();
void Input();
private:
char m_szNum[20];
int m_nAge;
};
#endif // !defined(AFX_STUDENT_H__E0DF041B_A9A3_46F4_B7E0_1CAA9AF3D392__INCLUDED_)
记录下老师讲的知识点,方便以后回顾,又感觉自己萌萌哒!