![]() |
#2
laoyang1032010-11-22 15:09
|
Array.h
Array.cpp
main.cpp

这个是Array.h文件中的内容
#ifndef ARRAY_H_H
#define ARRAY_H_H
enum Erro
{
IndexOutOf,
InviladArraySize,
MemoryAllocationErro
};
template<class T>
class Array
{
public:
Array(int size=20);
Array(Array<T>& _array);
~Array();
T& operator [](int i);
operator T*();
void ReSize(int sz);
int GetLength();
private:
void PrintErro(Erro erro);
int size;
T* data;
};
#endif
这个是Array.cpp文件中的内容
#include "Array.h"
#include <iostream.h>
#include "stdlib.h"
#define NULL 0
char* ErroInfo[]={"下标出界","数组大小不正确","申请内存失败"};
template <class T>
Array<T>::Array(int size1)
{
if(size1<0)
{
PrintErro(InviladArraySize);
}
size=size1;
data=new T[size1];
if(NULL==data)
{
PrintErro(MemoryAllocationErro);
exit(1);
}
}
template <class T>
Array<T>::Array(Array<T>& A_rray)
{
size= A_rray.size;
data=new T[size];
if(NULL==data)
{
PrintErro(MemoryAllocationErro);
exit(1);
}
else
{
for(int i=0;i<size;i++)
{
data[size]=A_rray.data[size];
}
}
}
template <class T>
T& Array<T>:: operator [](int i)
{
if(i>size || i<0)
{
PrintErro(IndexOutOf);
exit(1);
}
return data[i];
}
template <class T>
Array<T>::operator T*()
{
return data;
}
template <class T>
int Array<T>::GetLength()
{
cout<<"元素个数 : "<<size<<endl;
return size;
}
template <class T>
void Array<T>::ReSize(int sz)
{
if(sz<NULL)
{
PrintErro(MemoryAllocationErro);
exit(1);
}
else if(sz<size)
{
size=sz;
T* newdata=new T[sz];
if(NULL==newdata)
{
PrintErro(MemoryAllocationErro);
exit(1);
}
T* pb=data;
T* pn=newdata;
while(sz--)
{
*pb++=*pn++;
}
delete []data;
data=newdata;
}
else if(sz>size)
{
size=sz;
int count=size;
T* newdata=new T[sz];
if(NULL==newdata)
{
exit(1);
}
T* pb=data;
T* pn=newdata;
while(count--)
{
*pb++=*pn++;
}
delete []data;
data=newdata;
}
}
template <class T>
void Array<T>::PrintErro(Erro erro)
{
cout<<ErroInfo[erro]<<endl;
}
template <class T>
Array<T>::~Array()
{
delete []data;
}
这个是主程序文件main.cpp文件中的内容
#include "Array.h"
#include <iostream.h>
void main()
{
Array<int> hello(1);
hello[0]=10;
hello[1]=20;
cout<<"hello [0] "<<hello[0]<<endl;
cout<<"hello [1] "<<hello[1]<<endl;
}
这个是错误
--------------------Configuration: 11 - Win32 Debug--------------------
Compiling...
main.cpp
Linking...
main.obj : error LNK2001: unresolved external symbol "public: __thiscall Array<int>::~Array<int>(void)" (??1?$Array@H@@QAE@XZ)
main.obj : error LNK2001: unresolved external symbol "public: int & __thiscall Array<int>::operator[](int)" (??A?$Array@H@@QAEAAHH@Z)
main.obj : error LNK2001: unresolved external symbol "public: __thiscall Array<int>::Array<int>(int)" (??0?$Array@H@@QAE@H@Z)
Debug/11.exe : fatal error LNK1120: 3 unresolved externals
Error executing link.exe.
11.exe - 4 error(s), 0 warning(s)