怎样在模板类中声明友元函数,然后在类外定义?

假如我要定义一个链表模板类,在类里面定义了个Node类作为节点,节点包含了数据和下一节点的指针,然后重载一个输出运算符作为友元函数,如何定义这个类
template<class T>
7 class MyList
8 {
9 public:
10 class Node;
11 public:
12 MyList(void):n(0),head(NULL){}
13 ~MyList();
14 bool Empty(void);
15 int Size(void);
16 bool push_back(T d);
17 bool push_front(T d);
18 bool pop_back();
19 bool pop_front();
20 void sort();
21 friend ostream& operator<< <T>(ostream& os,const MyList& l);
22
23 public:
24 class Node
25 {
26 public:
27 Node(T d=T(0),Node* n=NULL):data(d),next(n){}
28 T data;
29 Node* next;
30 };
31 int n;
32 Node* head;
33 };
主要是这个友元函数怎么实现?

    程序如下:

    template <class T>

    ostream & operator << (ostream &os, const MyList <T> & l)

    {

    ListNode<T> * current = MyList <T> .head;

    while (NULL != current)

    {

    cout << current -> data >> " ";

    current = current -> next;

    }

    return ostream;

    }

    友元函数和普通函数区别:它能够操作类中的私有成员; 

    友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数。类授予它的友元特别的访问权。

    类外定义:

    在类的外面进行函数定义。

    如:class Student{public : void display( ); //公用成员函数原型声明private : int num; string name; char sex; //以上3行是私有数据成员};void Student::display( )//在类外定义display类函数{ cout<<"num:"<<num<<endl; cout<<"name:"<<name<<endl; cout<<"sex:"<<sex<<endl;}Student stud1,stud2; //定义两个类对象

    注意:在类体中直接定义函数时,不需要在函数名前面加上类名,因为函数属于哪一个类是不言而喻的。

温馨提示:内容为网友见解,仅供参考
第1个回答  2012-06-14
template <class T>
ostream & operator << (ostream &os, const MyList <T> & l)
{
ListNode<T> * current = MyList <T> .head;
while (NULL != current)
{
cout << current -> data >> " ";
current = current -> next;
}
return ostream;
}
1: 为什么你写了那么多的 public, 按照你的 程序, 后面的两个public 都可以不要的;
2:友元函数和普通函数区别 就是它能够操作 类中的私有成员; 你这个在说明它是个模板就可以;
3:friend ostream& operator<< <T>(ostream& os,const MyList& l);
改为 friend ostream& operator<< (ostream& os,const MyList<T>& l);
4:我就认为这样了。。。。追问

后面两个public错了,忘改了,我试试,先谢了

追答

恩。。。

追问

好像那样也不行,编译会报错

追答

恩,这个我也不知道,你能不能把你的源代码贴上来看下;
这个 我以前也写过。。。。