类模板案例
- MyArr.hpp:
#pragma once
template<typename T>
class MyArr {
public:
//有参构造-容量
MyArr(int capacity) {
//cout << "myArr有参构造调用" << endl;
this->m_capacity = capacity;
this->m_size = 0;
this->pArrAddress = new T[this->m_capacity];
}
//拷贝构造函数--因为为拷贝构造,所以传入的对象指针需要用const锁定
MyArr(const MyArr& arr) {
//cout << "拷贝构造函数调用" << endl;
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
//这属于浅拷贝,容易出现问题,因为数组的首地址是不可以进行更改的;
//this->pAddress = arr.pArrAddress;
//深拷贝
this->pArrAddress = new T[this->m_capacity];
//将arr中的数据拷贝过来
for (int i = 0; i < arr.m_capacity; i++) {
this->pArrAddress[i] = arr.pArrAddress[i];
}
}
//MyArr中的operator=运算符重载——防止浅拷贝的问题
MyArr& operator=(const MyArr& arr) {
//cout << "operator=函数调用" << endl;
//因为拷贝涉及数组的容量问题,所以需要重新根据拷贝的对象容量大小进行创建再赋值
//先判断原来堆区是否有数据,如果有先释放