Skip to content

MyArry

cpp
#pragma once  
#include <iostream>  
  
using namespace std;  
  
template<class T>  
class MyArray{  
public:  
//构造函数  
MyArray(int capacity){  
this->m_Capacity = capacity;  
this->m_Size = 0;  
this->pAddress = new T[this->m_Capacity];  
}  
  
//拷贝构造函数(深拷贝)  
MyArray(const MyArray& arr){  
this->m_Size = arr.m_Size;  
this->m_Capacity = arr.m_Capacity;  
  
//深拷贝  
this->pAddress = new T[arr.pAddress];  
  
//把arr中数据拷贝  
for (int i = 0; i < this->m_Size; ++i) {  
this->pAddress[i] = arr.pAddress[i];  
}  
}  
  
//operator= 防止浅拷贝问题  
MyArray& operator=(const MyArray& arr){  
//先判断原来堆区是否有数据,有就释放  
if(this->pAddress != NULL){  
delete[] this->pAddress;  
this->pAddress =NULL;  
this->m_Size =0;  
this->m_Capacity = 0;  
}  
  
//深拷贝  
this->m_Capacity = arr.m_Capacity;  
this->m_Size = arr.m_Size;  
this->pAddress = new T[arr.pAddress];  
for (int i = 0; i < this->m_Size; ++i) {  
this->pAddress[i] = arr.pAddress[i];  
}  
return *this;  
}  
//尾插法  
void Push_Back(const T & val){  
//判断数组大小是否等于容量,若相等则无法插入,直接返回  
if(this->m_Capacity == this->m_Size){  
return;  
}  
  
//将val插入最后一个位置  
this->pAddress[this->m_Capacity] = val;  
//插入完成,size自增  
this->m_Size++;  
}  
  
//尾删法  
void Pop_Back(){  
//若数组为空直接return  
if(this->m_Size == 0){  
return;  
}  
  
this->m_Size--;  
}  
  
//通过下标访问数组元素  
T& operator[](int index){  
return this->pAddress[index];  
}  
  
//返回数组容量  
int getCapacity(){  
return this->m_Capacity;  
}  
  
//返回数组大小  
int getSize(){  
return this->m_Size;  
}  
  
//析构函数  
~MyArray(){  
if(this->pAddress != NULL){  
delete[] this->pAddress;  
this->pAddress = NULL;  
}  
}  
  
private:  
T * pAddress;  
int m_Size{};  
int m_Capacity{};  
};

评论区

欢迎留言、补充或勘误。

xiaoba.blog