c/c++ 模板函数实例讲解与分析
类模板1,模板类里的函数都是模板函数2,模板类里的函数,在类外面实现的时候,要用模板函数(方法:push_back)的方式实现,在类内部实现时,不需要用模板函数(方法:show)方式实现。3,用模板类实现单链表,类List是类ListNode的友元类;用友元函数重载了类Value的<<函数;显示链表的show方法在类外面定义的部分注释掉了。#include using namespace std; template class List; //节点 template class ListNode{ friend class List; public: ListNode():data(A()),next(NULL){} ListNode(A a,ListNode *n) : data(a),next(n){} private: A data; ListNode *next; }; //单链表 template class List{ public: List(); //尾插 bool push_back(A val); //显示链表 void show()const{ ListNode *n = first->next; while(NULL != n){ cout << n->data; n = n->next; } cout << "NULL" << endl; } private: ListNode *first; ListNode *last; size_t size; }; template List first = last = new ListNode last->next = NULL; size = 0; } //尾插 template bool List::push_back(A value){ ListNode *node = new ListNode; if(NULL == node) return false; node->data = value; node->next = NULL; last->next = node; last = node; size++; return true; } //显示链表 /* template void List::show()const{ ListNode *n = first->next; while(NULL != n){ cout << n->data; n = n->next; } cout << "NULL" << endl; } */ class Value{ friend ostream& operator<<(ostream &o,const Value &v); public: Value(int d = 0) : value(d){} private: int value; }; ostream& operator<<(ostream &o,const Value &v){ o << v.value << "->"; return o; } int main(){ List for(int i = 0; i < 10; ++i){ l.push_back(Value(i)); } l.show(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |