手寫通用陣列
阿新 • • 發佈:2021-02-02
實現一個通用的陣列類,要求如下:
- 可以對內建資料型別以及自定義資料型別的資料進行儲存
- 將陣列中的資料儲存到堆區
- 建構函式中可以傳入陣列的容量
- 提供對應的拷貝建構函式以及operator=防止淺拷貝問題
- 提供尾插法和尾刪法對陣列中的資料進行增加和刪除
- 可以通過下標的方式訪問陣列中的元素
- 可以獲取陣列中當前元素個數和陣列的容量
程式碼結構
MyArray.hpp
#pragma once
#include<iostream>
using namespace std;
template<class T>
class MyArray
{
private :
T * pAddress;
int mCapacity;
int mSize;
public:
MyArray(int capacity)
{
this->mCapacity = capacity;
this->mSize = 0;
this->pAddress = new T[this->mCapacity];
}
MyArray(const MyArray& arr)
{
this->mCapacity = arr.mCapacity;
this->mSize = arr.mSize;
this-> pAddress = new T[arr.mCapacity];
for (int i = 0; i < this->mSize; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
MyArray& operator=(const MyArray& arr)
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->mCapacity = 0;
this->mSize = 0;
}
this->mCapacity = arr.mCapacity;
this->mSize = arr.mSize;
this->pAddress = new T[arr.mCapacity];
for (int i = 0; i < this->mSize; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
return *this;
}
void pushBack(const T& value)
{
if (this->mCapacity == this->mSize)
return;
this->pAddress[this->mSize] = value;
this->mSize++;
}
void popBack()
{
if (this->mSize == 0)
return;
this->mSize--;
}
T& operator[](int index)
{
return this->pAddress[index];
}
int getCapacity()
{
return this->mCapacity;
}
int getSize()
{
return this->mSize;
}
~MyArray()
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
};
陣列類封裝.cpp
#include<iostream>
using namespace std;
#include"MyArray.hpp"
void printArray(MyArray<int>& arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout << arr[i] << endl;
}
}
void test()
{
MyArray<int>arr(5);
for (int i = 0; i < 5; i++)
{
arr.pushBack(i);
}
cout << "array列印輸出:" << endl;
printArray(arr);
cout << "array1的大小:" << arr.getSize() << endl;
cout << "array1的容量:" << arr.getCapacity() << endl;
cout << "--------------------------" << endl;
MyArray<int>arr1(arr);
printArray(arr1);
arr1.popBack();
printArray(arr1);
}
int main()
{
test();
return 0;
}