STL3-MyArray动态数组类模板实现

注意

1、右值的拷贝使用

2、拷贝构造函数的使用 

#include
using namespace std;

template
class MyArray{
public:
	MyArray(int capacity)
	{
		this->mCapacity = capacity;
		this->mSize = 0;
		//申请内存
		this->pAddr = new T[this->mCapacity];
	}
	//拷贝构造
	MyArray(const MyArray& arr);  
	T& operator[](int index);
	MyArray operator=(const  MyArray& arr);
	void PushBack(T& data);
	//&&对右值取引用
	void PushBack(T&& data);
	~MyArray() {
		if (this->pAddr != NULL)
		{
			delete[] this->pAddr;
		}
		
	}
public:
	int mCapacity;  //数组容量
	int mSize;      //当前数组有多少元素
	T* pAddr;     //保存数组的首地址
};
template
MyArray::MyArray(const MyArray& arr)
{
	//我的 将原有数组拷贝到当前数组  错误
	/*arr->mCapacity = this->mCapacity;
	arr->mSize = this->mSize;
	arr->pAddr = new T[this->mCapacity];
	for (int i = 0; i < mSize; i++)
	{
		arr->pAddr[i] = this->pAddr[i];
	}
	*/

	//将arr拷贝到当前数组
	this->mCapacity = arr.mCapacity;
	this->mSize = arr.mSize;
	//申请内存空间
	this->pAddr = new T[this->mCapacity];
	//数据拷贝
	for (int i = 0; i < this->mSize; i++)
	{
		this->pAddr[i]=arr.pAddr[i];
	}
}
template
T& MyArray::operator[](int index)
{
	return this->pAddr[index];
}

template
MyArray MyArray::operator=(const MyArray& arr)
{
	//释放以前空间
	if (this->pAddr != NULL)
	{
		delete[] this - < pAddr;
	}
	this->mCapacity = arr.mCapacity;
	this->mSize = arr.mSize;
	//申请内存空间
	this->pAddr = new T[this->mCapacity];
	//数据拷贝
	for (int i = 0; i < this->mSize; i++)
	{
		this->pAddr[i] = arr->pAddr[i];
	}
	return *this;
}

template
void MyArray::PushBack(T& data)
{
	//判断容器中是否有位置
	if (this->mSize >= this->mCapacity)
	{
		return;
	}
	//调用拷贝构造 =号操作符
	//1、对象元素必须能够被拷贝
	//2、容器都是值寓意,而非引用寓意  向容器中放入元素都是放入元素的拷贝份
	//3、如果元素的成员有指针,注意 深拷贝和浅拷贝
	//深拷贝 拷贝指针 和指针指向的内存空间
	//浅拷贝 光拷贝指针
	this->pAddr[this->mSize] = data;
	mSize++;
}
#if 1
template
void MyArray::PushBack(T&& data)
{
	//判断容器中是否有位置
	if (this->mSize >= this->mCapacity)
	{
		return;
	}
	this->pAddr[this->mSize] = data;
	mSize++;
}
#endif

void test01()
{
	MyArray marray(20);
	
	int a = 10,b=20,c=30,d=40;
	marray.PushBack(a);
	marray.PushBack(b);
	marray.PushBack(c);
	marray.PushBack(d);
	//错误原因:不能对右值取引用
	//左值 可以在多行使用
	//右值 只能在当前行使用 一般为临时变量
	//增加void PushBack(T&& data)即可不报错
	marray.PushBack(100);
	marray.PushBack(200);
	marray.PushBack(300);


	for (int i = 0; i < marray.mSize; i++)
	{
		cout << marray.pAddr[i] << " ";
	}
	cout << endl;

	MyArray marray1(marray);  //拷贝构造函数使用
	cout << "myarray1:" << endl;
	for (int i = 0; i < marray1.mSize; i++)
	{
		cout << marray1.pAddr[i] << " ";
	}
	cout << endl;

	MyArray marray2=marray;  //=操作符的使用
	cout << "myarray2:" << endl;
	for (int i = 0; i < marray2.mSize; i++)
	{
		cout << marray2.pAddr[i] << " ";
	}
	cout << endl;
	
}
class Person{};
void test02()
{
	Person p1, p2;
	MyArray arr(10);
	arr.PushBack(p1);
	arr.PushBack(p2);

}

int main()
{
	test01();
	system("pause");
	return 0;
}

运行结果:

STL3-MyArray动态数组类模板实现_第1张图片

 

你可能感兴趣的:(stl,STL专栏)