类模板
类模板
以一个链表类模板作为例子
//Test1.h
#include<iostream> using namespace std; template<typename Type> class List; template<typename Type>//模板类作为友元类则得友元前声明 class Listnode { friend class List<Type>; private: Type a; Listnode<Type> *next; public: Listnode():a(Type()),next(NULL) {} Listnode(Type _a, Listnode<Type> *_next=NULL):a(_a),next(_next) {} ~Listnode(){} }; template<typename Type> class List { private: Listnode<Type> *first; Listnode<Type> *last; size_t size; public: List(); bool push_back(Type t); bool push_front(Type t); void print()const; bool delate(Type t); }; //////////////////////////////////////////////////// template<typename Type>//类模板的方法在外部实现的时候和函数模板基本相同, bool List<Type>::push_front(Type t)//都要使用template关键字,还有得在 类名后加上<模板参数> { Listnode<Type> *tmp = (Listnode<Type>*)malloc(sizeof(Listnode<Type>)); if(tmp != NULL) { tmp->a = t; if(this->size == 0) { this->first->next = tmp; tmp->next = NULL; this->last = tmp; } else { tmp->next = this->first->next; this->first->next = tmp; } ++this->size; return true; } else return false; } template<typename Type> bool List<Type>::delate(Type t) { if(this->first->next != NULL) { Listnode<Type> *p = this->first->next; Listnode<Type> *q = this->first; while(p != NULL) { if(p->a == t) { if(p->next != NULL) { q->next = p->next; p->next = NULL; } else { q->next = NULL; this->last = q; } --this->size; } else { q = p; p = p->next; continue; } p = q->next; } } return true; } template<typename Type> List<Type>::List() { first = last = (Listnode<Type>*)malloc(sizeof(Listnode<Type>)); last->next = NULL; this->size = 0; } template<typename Type> bool List<Type>::push_back(Type t) { Listnode<Type> *tmp = (Listnode<Type>*)malloc(sizeof(Listnode<Type>)); if(tmp == NULL) return false; tmp->a = t; tmp->next = NULL; this->last->next = tmp; this->last = tmp; ++this->size; return true; } template<typename Type> void List<Type>::print()const { if(this->size != 0) { Listnode<Type> *p = this->first->next; while(p != NULL) { cout<<p->a<<"->"; p = p->next; } cout<<"NUL."<<endl; } else { cout<<"List size is zero."<<endl; } return; }
实现了前插、尾插、print 和删除功能
//Test.cpp
#include"Test1.h" void main() { List<char> char_list; //<>内填入什么类型,就会构造那种类型的链表对象 for(int i=65; i<=69; ++i) { char_list.push_back(i); } char_list.print(); char_list.delate('B'); char_list.print(); List<int> int_list; for(int i=65; i<=69; ++i) { int_list.push_front(i); } int_list.delate(128); int_list.print(); }
运行结果
不积小流无以成江河