求助 关于模板类中的重载运算符的友元函数

lyac2006 2007-04-16 10:46:36
[root@localhost genDLLst]# g++ -o genDLLst2 genDLLst2.cpp
genDLLst2.cpp:41: warning: friend declaration `std::ostream& operator<<(std::ostream&, const DoublyLinkedList<T>&)' declares a non-template function
genDLLst2.cpp:41: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning

源代码如下:
#include<iostream>
using namespace std;
template<typename T>
class DLLNode {
public:
DLLNode() {
next = prev = 0;
}
DLLNode(const T& el, DLLNode *n = 0, DLLNode *p = 0) {
info = el; next = n; prev = p;
}
T info;
DLLNode *next, *prev;
};
template<typename T>
class DoublyLinkedList {
public:
DoublyLinkedList() {
head = tail = 0;
}
void addToDLLTail(const T&);
T deleteFromDLLTail();
~DoublyLinkedList() {
clear();
}
bool isEmpty() const {
return head == 0;
}
void clear();
void setToNull() {
head = tail = 0;
}
void addInMiddle(const T&);
void addToDLLHead(const T&);
T deleteFromDLLHead();
T& firstEl();
T* find(const T&) const;
void run();
protected:
DLLNode<T> *head, *tail;
friend ostream& operator<<(ostream&, const DoublyLinkedList<T>&);
};
template<typename T>
ostream& operator<<(ostream& out, const DoublyLinkedList<T>& dll) {
DLLNode<T> *tmp;
for (tmp = dll.head; tmp != 0; tmp = tmp->next)
out << tmp->info << ' ';
return out;
}
int main()
{
return 0;
}
...全文
322 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
loongee 2007-04-16
  • 打赏
  • 举报
回复
按taodm的方法将友元函数就地实现,警告消失。
loongee 2007-04-16
  • 打赏
  • 举报
回复
我在DEV C++ 下编译通过,不过有两个警告。
41 H:\C++\test.cpp [Warning] friend declaration `std::ostream& operator<<(std::ostream&, const DoublyLinkedList<T>&)' declares a non-template function
41 H:\C++\test.cpp [Warning] (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning
Thinkingking 2007-04-16
  • 打赏
  • 举报
回复
你需要在class DoublyLinkedList{.....}前面
申明class DoublyLinkedList;
pjy717 2007-04-16
  • 打赏
  • 举报
回复
我在VC2003下编译运行没有问题哦
taodm 2007-04-16
  • 打赏
  • 举报
回复
friend ostream& operator<<(ostream&, const DoublyLinkedList<T>&)
{
DLLNode<T> *tmp;
for (tmp = dll.head; tmp != 0; tmp = tmp->next)
out << tmp->info << ' ';
return out;
}
friend声明时就地实现。
taodm 2007-04-16
  • 打赏
  • 举报
回复
googel herb sutter的 Befriending Templates
lyac2006 2007-04-16
  • 打赏
  • 举报
回复
请问 为什么一定要就地实现?
飞哥 2007-04-16
  • 打赏
  • 举报
回复
不必理会

65,212

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧