模板的初级问题!在VC中不能运行。急救!多谢!
用VC6.0建立了一个win32 console application,然后加入了一个c++source文件template.cpp,在这个文件里编了以下语句,结果编译无错无警告,运行时却说:
“cann't execute program”
哪位大虾知道是什么原因吗?
下面是我的例子(从“21天学通C++”摘来的),多谢了
---------------
#include<iostream>
using namespace std;
const int DefaultSize=10;
class Animal
{
public:
Animal(int);
Animal();
~Animal(){}
int GetWeight() const {return itsWeight;}
void Display() const {cout<<itsWeight;}
private:
int itsWeight;
};
Animal::Animal(int weight):itsWeight(weight){}
Animal::Anima():itsWeight(0){}
template <class T>
class Array
{
public:
//constructors
Array(int itsSize=DefaultSize);
Array(const Array &rhs);
~Array(){delete [] pType;}
//operators
Array & operator=(const Array&);
T& operator[](int offSet){return pType[offSet];}
const T& operator[](int offSet) const{return pType[offSet];}
//accessors
int GetSize() {return itsSize;}
private:
T *pType;
int itsSize;
};
//implement the Constructor
template <class T>
Array<T>::Array(int size):itsSize(size)
{
pType=new T[size];
for (int i=0;i<size;i++)
pType[i]=0;
}
//copy constructor
template <class T>
Array<T>::Array(const Array &rhs)
{
itsSize=rhs.GetSize();
pType=new T[itsSize];
for(int i=0;i<itsSize;i++)
pType[i]=rhs[i];
}
//operator=
template <class T>
Array<T> & Array<T>::operator = (const Array & rhs)
{
if(this==&rhs)
return *this;
delete [] pType;
itsSize=rhs.GetSize();
pType=new T[itsSize];
for(i=0;i<itsSize;i++)
pType[i]=rhs[i];
return *this;
}
//driver program
int main()
{
Array<int> theArray;
Array<Animal> theZoo;
Animal * pAnimal;
//fill the arrays
for(i=0;i<theArray.GetSize ();i++)
{
theArray[i]=i*2;
pAnimal=new Animal(i*3);
theZoo[i]=*pAnimal;
delete pAnimal;
}
for (j=0;j<theArray.GetSize ();j++)
{
cout<<"theArray["<<j<<"]:\t";
cout<<theArray[j]<<"\t\t";
cout<<"theZoo["<<j<<"]:\t";
theZoo[j].Display();
cout<<endl;
}
return 0;
}