在这里,我把类函数定义与声明分开了:
以下是类定义与类函数的声明:
// vector.h
#pragma once
#include <iostream>
#include <assert.h>
#include <string>
using namespace std;
template <class T>
class Vector
{
public:
Vector()
:_start(NULL)
,_finish(NULL)
,_endofstorage(NULL)
{}
~Vector()
{
delete[] _start;
_start = _finish = _endofstorage = NULL;
}
Vector(const Vector<T>& v);
Vector<T>& operator=(Vector<T>& v);
T& operator[](size_t pos);
void PushBack(T a);
void Insert(T a, int pos);
void PopBack();
void Erase(int pos);
int Size() const;
int Capacity();
int Empty();
void print();
protected:
void Expand(int size);
protected:
T* _start;
T* _finish;
T* _endofstorage;
};
以下是类函数的定义:
在类外定义类函数时要加上它所属的域,在使用模板时,这里它所属的域是Vector<T>,而不是Vector。
还有值得注意的是,再类外定义类函数时每个函数前都要加上template <class T>
//vector.cpp
#include <iostream>
#include "vector.h"
template <class T>
void Vector<T>::Insert(T a, int pos)
{
assert(pos >= 0 && pos <= Size());
if(Capacity() == 0)
Expand(1);
else if(Capacity() <= Size())
Expand(2*Capacity());
for(int i = Size() - 1; i >= pos; --i)
{
_start[i + 1] = _start[i];
}
_start[pos] = a;
++_finish;
return;
}
template <class T>
void Vector<T>::PushBack(T a)
{
Insert(a, Size());
}
template <class T>
void Vector<T>::Erase(int pos)
{
assert(pos < Size() && pos >= 0);
if(Size() == 0)
return;
for(int i = pos; i < Size() - 1; ++i)
{
_start[i] = _start[i+1];
}
--_finish;
}
template <class T>
void Vector<T>::PopBack()
{
Erase(Size() - 1);
}
template <class T>
int Vector<T>::Size() const
{
return _finish - _start;
}
template <class T>
int Vector<T>::Capacity()
{
return _endofstorage - _start;
}
template <class T>
void Vector<T>::Expand(int size)
{
if(size > Capacity())
{
T* new_start = new T[size];
int sz = Size();
for(int i = 0; i < sz; ++i)
{
new_start[i] = _start[i];
}
delete[] _start;
_start = new_start;
_finish = _start + sz;
_endofstorage = _start + size;
}
return;
}
template <class T>
int Vector<T>::Empty()
{
return Size() == 0;
}
template <class T>
void Vector<T>::print()
{
cout<<"数组中元素为:"<<endl;
int i = 0;
for(; i < Size(); ++i)
{
cout<<i<<":"<<_start[i]<<" ";
}
cout<<endl;
}
template <class T>
Vector<T>::Vector(const Vector<T>& v)
{
if(v.Size() > 0)
{
int sz = v.Size();
T* tmp = new T[sz];
for(int i = 0; i < sz; ++i)
{
tmp[i] = v._start[i];
}
_start = tmp;
_finish = _start + sz;
_endofstorage = _finish;
}
else
_start = _finish = _endofstorage = NULL;
}
template <class T>
Vector<T>& Vector<T>::operator=(Vector<T>& v)
{
if(this != &v)
{
if(v.Size() == 0)
{
_finish = _start;
}
if(v.Size() > Size())
Expand(v.Size());
int sz = v.Size();
for(int i = 0; i < sz; ++i)
{
_start[i] = v._start[i];
}
_finish = _start + sz;
}
return *this;
}
template <class T>
T& Vector<T>::operator[](size_t pos)
{
assert(pos > 0 && pos < Size());
return _start[pos];
}