第16章 模板与泛型编程(10)
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的专栏
补充:软件开发 , C++ ,