p237.cpp
来自「《C++编程指南(续编)》的一些程序源代码」· C++ 代码 · 共 121 行
CPP
121 行
#include <iostream.h>
template <class T>
class Vector
{
public:
Vector(int nSize=0);
T& operator[](int nIndex);
T operator[](const int nIndex)const;
Vector(Vector& v);
Vector& operator=(Vector& v);
~Vector();
protected:
T* pData;
int nElems;
void allocate(int nS);
void assign(Vector& v);;
};
template <class T>
void Vector<T>::allocate(int nS)
{
nElems=nS;
pData=0;
if(nElems)
{
pData=new T[nS];
}
}
template <class T>
void Vector<T>::assign(Vector<T>& v)
{
delete pData;
pData=0;
allocate(v.nElems);
int nI;
for(nI=0;nI<nElems;nI++)
{
pData[nI]=v.pData[nI];
}
}
template <class T>
Vector<T>::Vector(int nS)
{
allocate(nS);
}
template <class T>
Vector<T>::Vector(Vector& v)
{
pData=0;
assign(v);
}
template<class T>
Vector<T>& Vector<T>::operator=(Vector<T>& v)
{
assign(v);
return *this;
}
template<class T>
Vector<T>::~Vector()
{
delete pData;
}
template<class T>
T& Vector<T>::operator[](int nIndex)
{
if(nIndex<0||nIndex>=nElems)
{
cout<<"Illegal index"<<endl;
nIndex=0;
}
return pData[nIndex];
}
template<class T>
T Vector<T>::operator[](const int nIndex)const
{
Vector<T>& curr=*(Vector<T>*)this;
return curr[nIndex];
}
int main(int argc,char ** argv)
{
int nSize=100;
Vector<int> v1(nSize);
int n1;
for(n1=0;n1<nSize;n1++)
{
v1[n1]=100-n1;
cout<<v1[n1]<<" ";
}
cout<<endl;
int n2;
Vector<int> v2(10);
v2=v1;
for(n2=0;n2<10;n2++)
cout<<v2[n2]<<" ";
cout<<endl;
Vector<char> v3(100);
v3[0]=v1[0];
cout<<v3[0];
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?