要求
- 可以对内置数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数中可以传入数组的容量
- 提供对应的拷贝构造函数以及
operator=
防止浅拷贝问题 - 提供尾插法和尾删法对数组中的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获取数组中当前元素个数和数组的容量
实现
template<class T>
class MyArray{
public:
MyArray(int capacity){
this->m_capacity = capacity;
this->m_size = 0;
this->m_addr = new T[this->m_capacity];
}
MyArray(const MyArray& arr){
if(arr.m_addr == NULL){
return;
}
// 深拷贝
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
this->m_addr = new T[this->m_capacity];
for(int i = 0; i < m_size; ++i){
// T 类型是可拷贝的,= 运算符也是深拷贝
this->m_addr[i] = arr.m_addr[i];
}
}
MyArray& operator=(const MyArray& arr){
if(this == &arr){
return *this;
}
if(this->m_addr != NULL){
delete[] this->m_addr;
this->m_addr = NULL;
this->m_capacity = 0;
this->m_size = 0;
}
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
this->m_addr = new T[this->m_capacity];
for(int i = 0; i < this->m_size; ++i){
this->m_addr[i] = arr.m_addr[i];
}
return *this;
}
T& operator[](int index){
return this->m_addr[index];
}
void pushBack(T& data){
if(this->m_size == this->m_capacity){
return;
}
this->m_addr[this->m_size] = data;
this->m_size++;
}
// 可以接收右值引用
void pushBack(T&& data){
if(this->m_size == this->m_capacity){
return;
}
this->m_addr[this->m_size] = data;
this->m_size++;
}
// 这种方式也可以接收右值引用
void pushBack(const T& data){
if(this->m_size == this->m_capacity){
return;
}
this->m_addr[this->m_size] = data;
this->m_size++;
}
void popBack(){
if(this->m_size == 0){
return;
}
this->m_size--;
}
int getCapacity() const{
return m_capacity;
}
int getSize() const{
return m_size;
}
~MyArray(){
if(this->m_addr != NULL){
delete[] this->m_addr;
this->m_addr = NULL;
this->m_size = 0;
}
}
private:
int m_capacity;
int m_size;
T *m_addr;
};
int main()
{
int a = 10, b = 20, c = 30;
MyArray<int> arr(10);
arr.pushBack(a);
arr.pushBack(b);
arr.pushBack(c);
arr.pushBack(100);
arr.pushBack(200);
for(int i = 0; i < arr.getSize(); ++i){
cout << arr[i] << " ";
}
cout << endl << "-----------" << endl;
arr.popBack();
for(int i = 0; i < arr.getSize(); ++i){
cout << arr[i] << " ";
}
cout << endl << "+++++++++++" << endl;
MyArray<int> arr2(arr);
for(int i = 0; i < arr2.getSize(); ++i){
cout << arr2[i] << " ";
}
cout << endl << "+++++++++++" << endl;
MyArray<int> arr3(5);
arr3.pushBack(1);
arr3.pushBack(2);
arr3.pushBack(3);
arr2 = arr3;
for(int i = 0; i < arr2.getSize(); ++i){
cout << arr2[i] << " ";
}
return 0;
}
输出:
10 20 30 100 200
-----------
10 20 30 100
+++++++++++
10 20 30 100
+++++++++++
1 2 3