16.4.4 Queue和QueueItem的友元聲明
1. 將類模板設為友元
template <class Type>
class QueueItem
{
QueueItem(const Type &t):item(t), next(0){}
Type item;
QueueItem *next;
friend class Queue<Type>;
};
template <class Type>
class QueueItem
{
QueueItem(const Type &t):item(t), next(0){}
Type item;
QueueItem *next;
friend class Queue<Type>;
};2. Queue輸出操作符
template <class Type>
ostream& operator<<(ostream &os, const Queue<Type> &q)
{
os<<"< ";
QueueItem<Type> *p;
for(p=q.head;p!=0;p=p->next)
{
os<<p->item<<" ";
}
os<<">";
return os;
}
template <class Type>
ostream& operator<<(ostream &os, const Queue<Type> &q)
{
os<<"< ";
QueueItem<Type> *p;
for(p=q.head;p!=0;p=p->next)
{
os<<p->item<<" ";
}
os<<">";
return os;
}3. 將函數模板設為友元
template <class Type>
class QueueItem
{
Type item;
QueueItem *next;
QueueItem(const Type &t):item(t), next(0){}
friend class Queue<Type>;
friend ostream &operator<< <Type>(ostream &os, const Queue<Type> &q);
};
template <class Type>
class QueueItem
{
Type item;
QueueItem *next;
QueueItem(const Type &t):item(t), next(0){}
friend class Queue<Type>;
friend ostream &operator<< <Type>(ostream &os, const Queue<Type> &q);
};template <class Type>
class Queue
{
public:
Queue():head(0), tail(0){}
Queue(const Queue &Q):head(0), tail(0)
{copy_elems(Q);}
Queue& operator=(const Queue&);
~Queue(){destroy();}
Type& front()
{return head->item;}
const Type &front() const{return head->item;}
void push(const Type &);
void pop();
bool empty() const
{return head==0;}
friend ostream &operator<< <Type>(ostream &os, const Queue<Type> &q);
private:
QueueItem<Type> *head;
QueueItem<Type> *tail;
void destroy();
void copy_elems(const Queue&);
};
template <class Type>
class Queue
{
public:
Queue():head(0), tail(0){}
Queue(const Queue &Q):head(0), tail(0)
{copy_elems(Q);}
Queue& operator=(const Queue&);
~Queue(){destroy();}
Type& front()
{return head->item;}
const Type &front() const{return head->item;}
void push(const Type &);
void pop();
bool empty() const
{return head==0;}
friend ostream &operator<< <Type>(ostream &os, const Queue<Type> &q);
private:
QueueItem<Type> *head;
QueueItem<Type> *tail;
void destroy();
void copy_elems(const Queue&);
};4. 類型依賴性與輸出操作符
綁定到Queue且使用Queue輸出操作符的每種類型本身必須有輸出操作符。
摘自 xufei96的專欄