注意
1、右值的拷贝使用
2、拷贝构造函数的使用
#include<iostream>
using namespace std;template<class T>
class MyArray{
public:MyArray(int capacity){this->mCapacity = capacity;this->mSize = 0;//申请内存this->pAddr = new T[this->mCapacity];}//拷贝构造MyArray(const MyArray<T>& arr); T& operator[](int index);MyArray<T> operator=(const MyArray<T>& 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<class T>
MyArray<T>::MyArray(const MyArray<T>& 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<class T>
T& MyArray<T>::operator[](int index)
{return this->pAddr[index];
}template<class T>
MyArray<T> MyArray<T>::operator=(const MyArray<T>& 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<class T>
void MyArray<T>::PushBack(T& data)
{//判断容器中是否有位置if (this->mSize >= this->mCapacity){return;}//调用拷贝构造 =号操作符//1、对象元素必须能够被拷贝//2、容器都是值寓意,而非引用寓意 向容器中放入元素都是放入元素的拷贝份//3、如果元素的成员有指针,注意 深拷贝和浅拷贝//深拷贝 拷贝指针 和指针指向的内存空间//浅拷贝 光拷贝指针this->pAddr[this->mSize] = data;mSize++;
}
#if 1
template<class T>
void MyArray<T>::PushBack(T&& data)
{//判断容器中是否有位置if (this->mSize >= this->mCapacity){return;}this->pAddr[this->mSize] = data;mSize++;
}
#endifvoid test01()
{MyArray<int> 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<int> marray1(marray); //拷贝构造函数使用cout << "myarray1:" << endl;for (int i = 0; i < marray1.mSize; i++){cout << marray1.pAddr[i] << " ";}cout << endl;MyArray<int> 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<Person> arr(10);arr.PushBack(p1);arr.PushBack(p2);}int main()
{test01();system("pause");return 0;
}
运行结果: