有关重载友元<<的问题,麻烦各位指点一下

Beover1984 2003-10-23 10:42:06
//LinearList.h

#include<iostream>

using namespace std;

template<class T>
class LinearList{
friend ostream& operator<<( ostream &out, const LinearList<T> &x );
public:
LinearList( int Msize = 10 );
~LinearList() { delete [] _elem; }

bool isEmpty()const { return _length == 0; }
int length()const { return _length; }
bool find( int k, T &x )const;
int search( const T &x )const;

LinearList<T>& del( int k, T &x );
LinearList<T>& insert( int k, const T &x);
private:
int _length;
int _max_size;
T *_elem;
};
template<class T>
ostream& operator<<( ostream &out, const LinearList<T> &x )
{
for( int i = 0; i < _length; ++i ){
out<< _elem[i] << ",";
}
out<< endl;
return out;
};


//test.cpp

#include<stdlib.h>
#include<iostream>
#include"LinearList.h"

using namespace std;

int main()
{
try{
LinearList<int> l(5);
cout<< " length = " << l.length() << "\n"
<< " isEmpty = " << l.isEmpty() << "\n";
l.insert( 0, 2 ).insert( 0 , 6 );
cout<< " length = " << l.length() << "\n"
<< " isEmpty = " << l.isEmpty() << "\n";
int z;
l.find( 1, z );
cout<< " first element is " << z << "\n"
<< " length = " << l.length() << "\n";
l.del(1, z );
cout<< " delete element is " << z << "\n"
<< " list is " << l << endl;
}
catch(...) {
cerr<< "an exception has occurred" << endl;
}
system( "pause" );
}

编译出错:
25 D:\cpp\LinearList.h
[Warning] friend declaration `class ostream & operator <<(ostream &, const LinearList<T> &)'
还有好多warning都是和这个友元<<有关的请各位看一下,谢谢了
...全文
23 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ttlb 2003-10-23
  • 打赏
  • 举报
回复
up Hot_Forever(用钱砸死我吧)
Hot_Forever 2003-10-23
  • 打赏
  • 举报
回复
看看这段:
template<class T>
ostream& operator<<( ostream &out, const LinearList<T> &x )
{
for( int i = 0; i < _length; ++i ){
out<< _elem[i] << ",";
}
out<< endl;
return out;
}
肯定是错的,为啥?你这里的_length是哪个对象的_length?,难道是ostream的?
这里定义了一个x对象也没用到,
然后你可能会写
for(int i=0;i<x._length;++i){
out<<x._elem[i]<<",";
}
对不起,无法将类的私有变量赋给i
ttlb 2003-10-23
  • 打赏
  • 举报
回复
找到错误了,声明改为:
template<class T>
friend ostream& operator<<( ostream &out, const LinearList<T> &x );
ttlb 2003-10-23
  • 打赏
  • 举报
回复
我看不出有什么错,operator << (ostream &, const T&) 没问题吧?

好多函数没有定义。
aflyinghorse 2003-10-23
  • 打赏
  • 举报
回复
改成下面的试试
friend ostream& operator<< <T>( ostream &out, const LinearList<T> &x );
langzi8818 2003-10-23
  • 打赏
  • 举报
回复
我看用分砸死你算了

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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