读书人

有些难模板类重载lt;lt;失败求指导

发布时间: 2013-04-09 16:45:09 作者: rapoo

有点难,模板类重载<<失败,求指导
#include<ostream>
#include<iostream>
#include<cstdlib>

using namespace std;

template<class T>
class Node
{
public:
T data;
Node<T> *next;
Node()
{
this->next=NULL;
}
Node(T data,Node<T> *next=NULL)
{
this->data=data;
this->next=next;
}
};


template <class T>
class CirHSLinkedList
{
public:
Node<T> *head;
CirHSLinkedList();
//~CirHSLinkedList();
CirHSLinkedList(T value[],int n);
bool isEmpty();
void clear();
CirHSLinkedList<T>& operator=(CirHSLinkedList<T> &list);
CirHSLinkedList(CirHSLinkedList<T> &list);
friend ostream & operator << (ostream & out,CirHSLinkedList<T> &list);
};

template<class T>
CirHSLinkedList<T>::CirHSLinkedList(T value[],int n)
{
this->head=new Node<T>();
Node<T>*temp=head;
for(int i=0;i<n;i++)
{
temp->next=new Node<T>(value[i]);
temp=temp->next;
}

}
template<class T>
CirHSLinkedList<T>::CirHSLinkedList()
{
this->head=new Node<T>();
//head->next=head;
}
template<class T>
bool CirHSLinkedList<T>::isEmpty()
{
return head->next==NULL;
}
template<class T>
void CirHSLinkedList<T>::clear()
{
Node<T> *p=head->next;
while(p!=NULL)
{
Node<T> *q=p;
p=p->next;
delete q;
}
head->next=NULL;
}
template<class T>
CirHSLinkedList<T>& CirHSLinkedList<T>:: operator=(CirHSLinkedList<T> &list)
{
this->clear();
if(list.head!=NULL)
{
this->head=new Node<T>();
Node<T> *rear=this->head;
for(Node<T> *p=list.head->next;p!=NULL;p=p->next)//change to NULL
{
rear->next=new Node<T>(p->data);
rear=rear->next;
}
//rear->next=this->head;
}
return *this;
}
template<class T>
CirHSLinkedList<T>::CirHSLinkedList(CirHSLinkedList<T> &list)
{
this->head=NULL;
*this=list;
}
template<typename T>
ostream & operator << (ostream & ot,CirHSLinkedList<T> &list)
{
Node<T> *p=list.head->next;
ot<<"(";
while(p!=NULL)
{
ot<<p->data;
p=p->next;
if(p!=NULL)
ot<<",";
}
ot<<")\n";
return ot;
}

int main()
{
CirHSLinkedList<char> lista("abc",3);
CirHSLinkedList<char> listb(lista);
cout<<listb;
return 0;
}
[解决办法]
template<typename T>
friend ostream & operator << (ostream & out,CirHSLinkedList<T> &list);
[解决办法]

引用:
引用:除了编译错误,代码问题还是挺多。
1,尽量使用const
2,head不要动态分配,以减少麻烦。


3,operator= 要检查自我赋值

参考一下:-)
C/C++ code?123456789101112131415161718192021222324252627282930313233343536373839……



因为它是友元函数,不是类的成员,类的模板参数<T>对它没有用

读书人网 >C++

热点推荐