无聊的时候就阅读一下代码,下列代码涉及到基础的c++知识。 温故而知新。
#include<iostream> using namespace std; template <typename Object> class Vector{ private: int thesize; int theCapacity; Object *objects; public: //构造函数 Vector(int initsize = 0) : thesize(initsize),theCapacity(initsize+SPARE_CAPACITY)
{
objects = new Object[theCapacity];
} //拷贝构造函数 Vector(const Vector & rth) : objects(NULL) { // operator=(rth); cout<<"dd2"<<endl; //不相等删除现对象 if(this != &rth){ cout<<"dd"<<endl; // if(objects) // { // delete [] objects; // } //重新定义大小 thesize = rth.size(); theCapacity = rth.capacity(); //objects重新赋值 //objects = new Object[capacity()]; objects = new Object[theCapacity]; cout<<"ff"<<theCapacity<<endl; for(int i=0;i<size();i++) objects[i] = rth.objects[i]; } } //析构 ~Vector(){ // if(objects) delete [] objects; cout<<"析构"<<objects<<endl; delete []objects; objects=NULL; }; //赋值重载并拷贝 const Vector & operator= (const Vector & rth){ //不相等删除现对象 if(this != rth){ //if(objects) // { delete [] objects; // } //重新定义大小 thesize = rth.size(); theCapacity = rth.theCapacity(); //objects重新赋值 objects = new Object[capacity()]; for(int i=0;i<size();i++) objects[i] = rth.objects[i]; } return *this; } //重设大小 void resize(int newsize){ if(newsize>theCapacity) reserve(newsize*2 + 1); theSize = newsize; } // void reserve(int newcapacity){ if(newcapacity<thesize) return; Object *oldArry = objects; objects = new Object[newcapacity]; for(int i=0;i<thesize;i++) objects[i] = oldArry[i]; theCapacity = newcapacity; delete [] oldArry; } //[]运算符重载 Object & operator[](int index){ return objects[index]; } //[]运算符重载常量函数 const Object & operator[] (int index) const{ return objects[index]; } //判断是否为空 bool empty(){ return thesize() == 0; } //返回容器大小 int size() const{ return thesize; } //返回容器容量 int capacity() const{ return theCapacity; } //添加数据 void push_back(const Object & x){ if(thesize == theCapacity) reserve(theCapacity*2 + 1); objects[thesize++] = x; } //出数据 const Object & pop_back(){ theSize--;
if(theSize<0)
theSize=0;
return objects[theSize]=x;
} //取最后一个对象 const Object & back(){ return objects[theSize-1]; } //定义一个迭代对象指针 typedef Object * iterator; //定义一个迭代对象常量指针 typedef const Object * const_iterator; //返回容器的第一个迭代 iterator begin(){ return &objects[0]; } //返回容器的第一个迭代的常量函数 const_iterator begin() const{ return &objects[0]; } //返回容器的最后一个迭代 iterator end(){ return &objects[thesize()]; } //返回容器的最后一个迭代的常量涵数 const_iterator end() const{ return &objects[thesize()]; } enum{SPARE_CAPACITY}; }; int main(){ Vector<int> vint; //定义一个int 容器对象 //赋值 for(int i=0;i<10;i++) vint.push_back (i); cout<<"dfdf"<<endl; //将vint拷贝给vint2 Vector<int> vint2(vint); //将vint2赋值给vint3 //Vector<int> vint3; //vint3= vint; //输出vint的大小 cout<<vint.size ()<<endl; //输出vint的 cout<<vint.capacity ()<<endl; return 0; }