有点难,模板类重载<<失败,求指导
#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);
[解决办法]
因为它是友元函数,不是类的成员,类的模板参数<T>对它没有用