文章目录
- 功能
- 代码
- 运行结果
功能
利用模板进行数组类封装,在代码实现过程中,使用了
1.operator=重载,利用深拷贝防止浅拷贝问题;
2.operator[]重载,确保可以使用[]来仿真数组元素;
3.尾插法、尾删法、返回数组容量和数组大小;
代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
template<class T>
class MyArray
{
public:
/*有参构造*/
MyArray(int capacity)
{
/*cout << "构造" << endl;*/
this->m_Capacity = capacity;
this->m_size = 0;
this->pAddress = new T[this->m_Capacity];
}
/*拷贝构造*/
MyArray(const MyArray &arr)
{
/*cout << "拷贝构造" << endl;*/
this->m_Capacity = arr.m_Capacity;
this->m_size = arr.m_size;
/*深拷贝*/
this->pAddress = new T[arr.m_Capacity];
/*将arr中的数据拷贝过来*/
for (int i = 0; i < this->m_size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
/*operator= 防止浅拷贝问题*/
MyArray& operator=(const MyArray& arr)
{
/*cout << "operator=调用" << endl;*/
/*先判断原来堆区是否有数据,如果有先释放*/
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->m_Capacity = 0;
this->m_size = 0;
}
/*深拷贝*/
this->m_Capacity = arr.m_Capacity;
this->m_size = arr.m_size;
this->pAddress = new T[arr.m_Capacity];
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)
{
cout << "容量等于元素个数" << endl;
return;
}
this->pAddress[this->m_size] = val;/*在数据末尾插入数据*/
this->m_size++;/*更新数组大小*/
}
/*尾删法*/
void Pop_Back()
{
/*让用户访问不到最后一个元素,即为尾删,逻辑删除*/
if (this->m_size == 0)
{
cout << "元素个数为0,不执行尾删!" << endl;
}
this->m_size--;
}
/*通过下标方式访问数组中的元素*/
T& operator[](int index)
{
return this->pAddress[index];
}
/*返回数组容量*/
int GetCapaCity()
{
return this->m_Capacity;
}
/*返回数组大小*/
int GetSize()
{
return this->m_size;
}
/*析构函数*/
~MyArray()
{
/*cout << "析构" << endl;*/
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
private:
T* pAddress;
int m_Capacity;
int m_size;
};
void printMyArray(MyArray<int> &arr)
{
/*使用了arr.GetSize()*/
for (int i = 0; i < arr.GetSize(); i++)
{
/*使用了[]重载*/
cout << arr[i] << " ";
}
cout << endl;
}
void test01()
{
MyArray<int>arr1(10);
/*利用尾插法向数组中插入数据*/
for (int i = 0; i < 5; i++)
{
arr1.Push_Back(i);
}
cout << "arr1中的数据打印:";
printMyArray(arr1);
cout << "arr1的容量: " << arr1.GetCapaCity() << endl;
cout << "arr1的大小: " << arr1.GetSize() << endl;
/*利用拷贝构造*/
MyArray<int>arr2(arr1);
cout << "--------------------" << endl;
cout << "arr2中的数据打印:";
printMyArray(arr2);
cout << "arr2的容量: " << arr2.GetCapaCity() << endl;
cout << "arr2的大小: " << arr2.GetSize() << endl;
cout << "arr2尾删后的数据打印 ";
arr2.Pop_Back();
printMyArray(arr2);
return;
}
int main()
{
test01();
return 0;
}