是用游标来实现表的头文件,随手写的,所以把类的申明和类的实现都写在一起了,问题主要是友元声明的问题,不声明友元的的话,把node类的成员改成公有的也行。不用模板就没问题,真是搞不懂。我改了好久也没改好,望大家帮帮忙! #include <iostream.h>
class OutOfBounds; class NoMen;
template <class t> class Node { friend Space<t>; //声明友元出现问题 friend Yblist<t>; private: t date; int next; }; ///////////////////////////////////////////////////////////////////////////////////////////////// template <class t> class Space { friend Yblist<t>; //声明友元出现问题 public: Space(int m=100); ~Space() {delete []a;} int Allocate(); void Deallocate(int i); int num,f1,f2; Node<t> *a; };
template <class t> Space<t>::Space(int m) { num=m; a=new Node<t>[num]; f1=0; f2=-1; }
template <class t> int Space<t>::Allocate() { if(f2==-1) { if(f1==num) throw NoMen(); return f1++; } int i=f2; f2=a[i].next; return i; }
template <class t> void Space<t>::Deallocate(int i) { a[i].next=f2; f2=i; } ///////////////////////////////////////////////////////////////////////////////////////////////// template <class t> class Yblist { public: Yblist() {first=-1;} ~Yblist(); int Length() const; bool Retrieve(int k,const t &x) const; int Locate(const t &x) const; Yblist<t> &Insert(int k,const t &x); Yblist<t> &Delete(int k); void Show(ostream &out) const; private: int first; Space<t> s;
};
template <class t> Yblist<t>::~Yblist() { int next; while(first!=-1) { next=s.a[first].next; s.Deallocate(first); first=next; } }
template <class t> int Yblist<t>::Length() const { int len=0; int next=first; while(next!=-1) { next=s.a[next].next; len++; } return len; }
template <class t> bool Yblist<t>::Retrieve(int k,const t &x) const { if(k<1) return false; int next=first,index=1; while(index<k && next!=-1) { next=s.a[next].next; index++; } if(next!=-1) { x=s.a[next].data; return true; } return false; }
template <class t> int Yblist<t>::Locate(const t &x) const { int next=first,index=1; while(next!=-1 && s.a[next].data!=x) { next=s.a[next].next; index++; } return (next!=-1? index: 0); }
template <class t> Yblist<t> &Yblist<t>::Insert(int k,const t &x) { if(k<0) throw OutOfBounds(); int p=first; for(int index=1;index<k && p!=-1;index++) p=s.a[p].next; if(k>0 && p==-1) OutOfBounds(); int y=s.Allocate(); s.a[y].data=x; if(k) { s.a[y].next=s.a[p].next; s.a[p].next=y; } else { s.a[y].next=first; first=y; } return *this; }
template <class t> Yblist<t> &Yblist<t>::Delete(int k) { if(k<1 || first==-1) throw OutOfBounds(); int p=first; if(k=1) first=s.a[first].next; else { for(int index=1;index<k-1 && p!=-1; index++) p=s.a[p].next; if(p==-1 && s.a[p].next==-1) throw OutOfBounds(); int i=s.a[p].next; s.a[p].next=s.a[i].next; } s.Deallocate(i); return *this; }
template <class t> void Yblist<t>::Show(ostream &out) const { for(int p=first;p!=-1;p=s.a[p].next) out<<s.a[p].data<<' '; out<<endl; }