模板类的友元问题,有个问题条是不通过,请教
原码如下:
#include <iostream>
#include<string>
using namespace std;
template <class T>
class Array
{
private:
T* pArray;
int size;
public:
Array(int nSize=30);
Array(const Array<T> &x);
~Array(){delete []pArray;}
Array<T> &operator=(const Array<T> &x);
T &operator[](int nCount);
int getSize(){return size;}
friend ostream& operator<<(ostream&, const Array<T>&);
};
template <class T>
Array<T>::Array(int nSize)
{
size=nSize;
pArray=new T[size];
if(pArray==0)
{
cout<<"MEMORY OUT!!"<<endl;
}
}
template <class T>
Array<T>::Array(const Array<T>&x)
{
size=x.size;
delete []pArray;
pArray=new T[size];
T *srcptr=x.pArray;
T *destptr=pArray;
int temp=size;
while(temp)
{
temp--;
destptr[temp]=srcptr[temp];
}
}
template <class T>
Array<T>& Array<T>::operator=(const Array<T> &x)
{
delete []pArray;
pArray=new T<x.getSize()>
T *srcptr=x.pArray;
T *destptr=pArray;
int temp=size;
while(temp)
{
temp--;
destptr[temp]=srcptr[temp];
}
return *this;
}
template <class T>
T & Array<T>::operator[](int nCount)
{
return pArray[nCount];
}
template <class T>
ostream& operator<<(ostream& os, const Array<T>& a)
{
for(int i=0;i<a.size; i++)
{
os<<a.pArray[i];
}
os<<endl;
return os;
}
///////////////////////////////////////
以下为测试程序:
void main()
{
Array<int> a(20);
for(int i=0;i<20;i++)
{
a[i]=i+1;
}
Array<int> b(a),c=a;
cout<<a;
}
//////////////////////////////////////
以下为错误信息:错误出在重载输出操作符上。
Compiling...
a.cpp
g:\download1\专用上传文件夹\daodao\a.cpp(69) : error C2248: 'size' : cannot access private member declared in class 'Array<int>'
g:\download1\专用上传文件夹\daodao\a.cpp(9) : see declaration of 'size'
g:\download1\专用上传文件夹\daodao\a.cpp(84) : see reference to function template instantiation 'class std::basic_ostream<char,struct std::char_traits<char> > &__cdecl operator <<(class std::basic_ostream<char,struct std::char_traits<char> >
&,const class Array<int> &)' being compiled
g:\download1\专用上传文件夹\daodao\a.cpp(71) : error C2248: 'pArray' : cannot access private member declared in class 'Array<int>'
g:\download1\专用上传文件夹\daodao\a.cpp(8) : see declaration of 'pArray'
g:\download1\专用上传文件夹\daodao\a.cpp(84) : see reference to function template instantiation 'class std::basic_ostream<char,struct std::char_traits<char> > &__cdecl operator <<(class std::basic_ostream<char,struct std::char_traits<char> >
&,const class Array<int> &)' being compiled
Error executing cl.exe.
a.obj - 2 error(s), 0 warning(s)