//函数声明部分
friend ostream& operator<<<>(ostream&,SinglyList<T>&); //输出单链表所有元素
//函数定义
template <class T>
ostream& operator<<<>(ostream &out,SinglyList<T> &list)
{
out<<"(";
for(Node<T> *next=list.head->next; next != NULL; next = next->next)
{
out<<next->data;
if(next->next != NULL)
out<<",";
}
out<<")\n";
return out;
}
g++ 编译时报错:
SinglyList.h:64:55: 错误:模板标识符‘operator<< <>’出现在基本模板的声明中
ostream& operator<<<>(ostream &out,SinglyList<T> &list)
SinglyList.h:20:19: 错误:‘std::ostream& operator<<(std::ostream&, SinglyList<Computer>&)’的模板标识符‘operator<< <>’不匹配任何模板声明
friend ostream& operator<<<>(ostream&,SinglyList<T>&); //输出单链表所有元素
这是我在书上看到的代码,在我的环境中编译报错。
首先对于“operator<<<>”这部分中的<>不明白代表什么意思?
先谢了。
你好 重载运算符直接 : 返回类型 + opreator + 运算符 +(参数,参数)
为什么有<>我也说不清,感觉不应该有这个才对(教科书上也有很多错误的代码)但是我写代码测试的发现,声明这个友元函数是加上<> 不会编译错误,而在定义函数的时候加上就会报错。这是编译通过的代码:
#include <stdio.h> #include <string.h> #include <iostream> #include <list> #include <stdlib.h> using namespace std; template<class T> class Test { public: friend ostream& operator << <>(ostream&, list<T>&); }; template<typename T> ostream& operator << (ostream &out,list<T> &list) { }
我的问题已经解决了,谢谢你。如果你想搞清楚<>,建议你看下c++ Primer这本书的模板那一章节。
下面是我分享的电子版的c++ Primer链接地址:
https://pan.baidu.com/s/1b7S3_Foese3ZXdmPYYRsIg
@wtsgtc: 好的,谢谢你!