我在重载"<<"的时候遇到一个问题,程序代码如下:
bcb6中编译
template< class T >
class LinearList
{
friend ostream& operator<<(ostream& out,const LinearList& list);
public:
//--------------------------------
private:
T* element;
};
template<class T>
ostream& operator <<(ostream& out, const LinearList<T>& list)
{
for(int i = 0; i < length; i++)
out<<list.element[i]<<" ";
return out;
}
可是编译不能通过,出现如下错误提示:
[Linker Error] Unresolved external operator <<(_STL::basic_ostream<char, _STL::char_traits<char> >&, const LinearList<char>&) referenced from E:\MYWORKS\CBPROJECTS\LITTLEAPPLES数据结构_抽象数据描述\MY_LINEARLIST\LINEARLIST_MAIN.OBJ
我不知道到底错在哪儿了:。。。。。
你的程序在VC.NET上可以通过。
我忘了说我上面说的在VC 6.0中是行不通的,原因:VC 6.0对标准的支持很差。
在 VC.NET 和 BCB 以及DEV-CPP中都可以顺利编译. 如果你用的是VC 6.0就换个支持标准的C++编译器吧!
#include<iostream>
using namespace std;
// forward declare
template< class T > class List;
// forward declare
template< class T >
ostream& operator<< ( ostream& os, List< T > &List );
template<class T>
class List
{
friend ostream& operator<< < T >(ostream& os, List<T>& list);
public:
List()
{
char* a = "I love you";
element = new T[10];
for( int i = 0; i < 10; i ++ )
element[i]=a[i];
}
~List()
{
delete[] element;
}
private:
T* element;
};
template<class T>
ostream& operator<< (ostream& os, List<T>& list)
{
for(int i = 0; i < 10; i++){
os<<list.element[i];
}
return os;
}
// Drive file:
#include <iostream>
#include <stdlib.h>
#include"CSDn_Qu1.h"
using namespace std;
int main()
{
List<char> alist;
cout<<alist;
return 0;
}