int main()
{
Vector<int> vec;
//添加元素
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(3);
vec.toString();
//弹出最后一个元素
vec.pop_back();
vec.toString();
//直接取某个元素
const int a = vec[0];
cout<<"vec[1]:"<<vec[1]<<endl;
return 0;
}
#include "stdafx.h"
#include <iostream>
using namespace std;
//template 关键字后接模板形参表,表明这里定义的Vector是一个类模板,而不是一个类,
//Vector<int>才是一个类.函数模板也是一样,它们都只是一个"公式".
template <typename Object>
class Vector
{
public:
static const int SPARE_CAPACITY = 16;
//将构造函数声明为explicit ,是为了抑制由构造函数定义的隐式转换
/*
构造函数的初始化列表.关于构造函数的初始化列表, 有两个要点.第一, 即使列表为空, 没有初始化式,
构造函数也会先初始化每个成员再进入函数体, 这时初始化的规则与初始化变量相同,
由此得知第二个要点:如果类的成员本身是一个没有默认构造函数的类类型, 或者成员是const、引用类型,
这样的成员必须在构造函数初始化列表中进行初始化
*/
explicit Vector(int initSize = 0) :theSize(initSize), theCapacity(initSize + SPARE_CAPACITY)
{
//new返回一个指向Object类型数组的指针
objects = new Object[theCapacity];
}
Vector(const Vector& rhs) :objects(NULL)
{
operator=(rhs);
}
~Vector()
{
delete[] objects;
}
const Vector& operator=(const Vector& rhs)
{
if (this != &rhs)
{
delete[] objects;
theSize = rhs.theSize;
theCapacity = rhs.theCapacity;
objects = new Object[theCapacity];
for (int k = 0; k < theSize; k++)
{
objects[k] = rhs.objects[k];
}
}
return *this;
}
/*
由于成员函数的定常性是(即函数名后是否有const关键字)是签名的一部分,
因此我们可以使用访问函数的operator[]版本返回const引用,而修改函数版本返回一般引用
*/
Object& operator[](int index)
{
if (index < 0 || index >= theSize)
{
return objects[0];
}
cout << "--Object& operator[](int index)"<<endl;
return objects[index];
}
const Object& operator[](int index)const
{
cout << "** const Object& operator[](int index)const" << endl;
return objects[index];
}
//检测是否需要扩容
void reserve()
{
reserve(theSize);
}
void reserve(int newSize)
{
if (theCapacity > newSize)
{
return;
}
int newCapacity = theCapacity * 2 + 1;
Object* oldArr = objects;
objects = new Object[newCapacity];
for (int k = 0; k < theSize; k++)
{
objects[k] = oldArr[k];
}
theCapacity = newCapacity;
delete[] oldArr;
}
int size()const
{
return theSize;
}
int capacity()const
{
return theCapacity;
}
bool empty()const
{
return theSize == 0;
}
void resize(int newSize)
{
reserve(newSize);
theSize = newSize;
theCapacity = newSize;
}
void push_back(const Object& obj)
{
reserve(); //检测容器大小
objects[theSize++] = obj;
}
void pop_back()
{
theSize--;
}
const Object & back()const
{
return objects[theSize - 1];
}
Object* begin()
{
return &objects[0];
}
Object* end()
{
return &objects[theSize];
}
const Object* end()const
{
return&objects[theSize];
}
void toString()
{
cout << "Vecot长度:" << size() << ",容量:" << capacity() << endl;
for (int i = 0; i < theSize; i++)
{
cout << "objects[" << i << "]:" << objects[i] << endl;
}
}
typedef Object* iterator;
typedef const Object* const_iterator;
private:
int theSize;
int theCapacity;
Object* objects;
};