链表之输出流重载
#include<iostream>
using namespace std;
template <typename T>struct node{
T data;
node<T> *next;
};
template <typename T>class LinkList{
private:
node<T> *head;
public:
LinkList()
{
head=new node<T>;
head->next=NULL;
}
friend ostream & operator <<(ostream & out ,LinkList <T>&);
};
template <class T>
ostream & operator <<(ostream & out ,LinkList<T> &a)
{
node <T> *p=a.head->next;
while(p!=NULL)
{
out<<p->data;
p=p->next;
}
return out;
}
int main()
{
LinkList<int> La;
cout<<La;
return 0;
}
编译出错,原因是: 无法解析的外部符号 "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class LinkList<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$LinkList@H@@@Z),该符号在函数 _main 中被引用
1>E:\C++ project\Link\Debug\Link.exe : fatal error LNK1120: 1 个无法解析的外部命令
是怎么回事啊?
[解决办法]
向前声明输出流操作符重载函数和模板类。
在类中的友元声明改写如下:
friend ostream & operator << <>(ostream & out ,LinkList <T>&);
[解决办法]
ostream函数的申明