理解向量vector的一些实现细节

#include 

using namespace std;

enum ErrorType
{
	invalidArraySize, memoryAllocFail, indexOutOfRange
};

const char*ErrorList[]={"invalidArraySize","memoryAllocFail","indexOutOfRange"};

template 
class MyVector
{
public:
	MyVector(int sz=50);
	MyVector(const MyVector& V);
	~MyVector();
	MyVector& operator=(const MyVector& V);
	T& operator[](int i);
	operator T*(); // 实现强制类型转换 MyVector---> T*;
	int Size();
	void resize(int sz);
	void Error(ErrorType err);
private:
	T *Array;
	int size;
};

template
void MyVector::Error(ErrorType err)
{
	cout << ErrorList[err] << endl;
	exit(1);
}

template
MyVector::MyVector(int sz)
{
	if(sz<=0)
	{
		Error(invalidArraySize);
	}
	else
	{
		size = sz;
		Array = new T[size];
		if(Array==NULL)
			Error(memoryAllocFail);
		
	}
	
}

template
MyVector::MyVector(const MyVector& V)
{
	int n = V.size;
	size = n;
	Array = new T[n];
	if(Array==NULL)
		Error(memoryAllocFail);

	T*org_array = Array;
	T*new_array = V.Array;

	while(n--)
		*org_array++ = *new_array++;
}

template
MyVector::~MyVector()
{
	delete [] Array;
}

template
MyVector& MyVector::operator=(const MyVector& V)
{
	int n = V.size;
	if(size!=n)
	{
		delete[] Array;
		size = n;
		Array = new T[size];
		if(Array==NULL)
			Error(memoryAllocFail);
	}

	T* org_Array = Array;
	T* new_Array = V.Array;

	while(n--)
		*org_Array++ = *new_Array++;

	return *this;
}

template
T& MyVector::operator[](int i)
{
	if(i<0 || i>=size)
		Error(indexOutOfRange);

	return Array[i];
}

template
MyVector::operator T*()
{
	return Array;
}

template
void MyVector::resize(int sz)
{
	if(sz<=0)
		Error(invalidArraySize);

	if(size == sz) return;

	int n=(sz
int MyVector::Size()
{
	return size;
}

int main()
{
	MyVector V1(5);

	for(int i=0; i>V1[i];

	MyVector V2 = V1;   // 拷贝构造函数,相当于V2(V1);
	MyVector V3;        // 默认构造函数
	V3 = V2;  // 复制运算 operator=

	MyVector V4(V3);    // 拷贝构造函数;

	cout << "V2======\n";
	for(int i=0; i

你可能感兴趣的:(C++)