注意
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++;
}
#endif
void 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;
}
运行结果:


本文介绍了一个模板类MyArray的详细实现过程,包括拷贝构造函数、赋值运算符重载、右值引用的使用等核心内容。通过具体示例展示了如何创建和使用该类,以及在不同场景下拷贝构造函数和赋值运算符的作用。

1206

被折叠的 条评论
为什么被折叠?



