帮别人回答问题发现自己原来也不懂`````向高手求助(关于友员模板的问题)

1982pc 2005-04-23 07:45:51
#include <iostream>
using namespace std;
template <class Type> class QueueItem;
template <class Type> class Queue;

template <class Type> ostream& operator<< ( ostream &, const Queue<Type>& );
template <class Type> ostream& operator<< ( ostream &, const QueueItem<Type>& );


template <class Type>
class QueueItem
{
friend class Queue<Type>;
friend ostream& operator<< ( ostream &, const QueueItem<Type>& ); //友元声明
public:
QueueItem( const Type& t ) : item(t) {next = 0;}

~QueueItem(){};
QueueItem *next;
private:
Type item;
};

template <class Type>
class Queue
{
friend ostream& operator<< ( ostream &, const Queue<Type>& );
public:
Queue() : front( 0 ), back( 0 ) { }
~Queue(){};
//友元声明
private:
QueueItem<Type> *front;
QueueItem<Type> *back;
};
// 只给出重载函数的定义, 其它函数的定义给略了

template <class Type> ostream& operator<< ( ostream &os, const Queue<Type> &q )
{
os << "< ";
QueueItem<Type> *p;
for( p=q.front; p; p=p->next)
os << *p << " ";
os << " >";
return os;
}
template <class Type> ostream& operator<< ( ostream &os, const QueueItem<Type>&qi )
{
os << qi.getItem();
return os;
}
int main()
{
QueueItem<int> iqi(3);
cout << iqi;
Queue<int> iq;

system("pause");
}
现在有三个警告如下:
16 C:\Dev-Cpp\C++-Test\main.cpp [Warning] friend declaration `std::ostream& operator<<(std::ostream&, const QueueItem<Type>&)' declares a non-template function

16 C:\Dev-Cpp\C++-Test\main.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

29 C:\Dev-Cpp\C++-Test\main.cpp [Warning] friend declaration `std::ostream& operator<<(std::ostream&, const Queue<Type>&)' declares a non-template function

一个错误:
[Linker error] undefined reference to `operator<<(std::ostream&, QueueItem<int> const&)'

警告是说:友员函数不是模板函数吗?
...全文
100 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
1982pc 2005-04-23
  • 打赏
  • 举报
回复
VC6.0对友员支持有问题,DC++4.9.9.2对友员模板函数又有问题~~~~~哎!!!!
1982pc 2005-04-23
  • 打赏
  • 举报
回复
但是在VC里它又会有友员报错!
item' : cannot access private member declared in class 'QueueItem<int>'
D:\C++\Cpp1.cpp(22) : see declaration of 'item'
难道还是编译器问题?!(我自己觉得好像是)


更正一个地方
template <class Type> ostream& operator<< ( ostream &os, const QueueItem<Type>&qi )
{
os << qi.item();
return os;
}
GuodongHe 2005-04-23
  • 打赏
  • 举报
回复
基本上和前一个同学提的问题一样,便宜器不支持摸板的摸板友元函数
zengwujun 2005-04-23
  • 打赏
  • 举报
回复
编译器的问题,vc是支持的

64,648

社区成员

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

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