myArray.hpp:
#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()
{
if (this->pAddress != NULL)
{
delete[]this->pAddress;
this->pAddress = NULL;
}
}
MyArray(const MyArray& arr)
{
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
//浅拷贝
//this->pAddress = arr.pAddress;
//深拷贝
this->pAddress = new T[arr.m_capacity];
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_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 PushBack(const T& val)
{
//判断容量是否等于大小
if (this->m_capacity == this->m_size)
{
return;
}
this->pAddress[this->m_size] = val;
this->m_size++;//更新数组大小
}
//尾删
void PopBack()
{//让用户访问不到最后一个元素,即为尾删,逻辑删除
if (this->m_size == 0)
{
return;
}
this->m_size--;
}
//通过下标访问数组中的元素 arr[0]=100
T& operator[](int index)
{
return this->pAddress[index];
}
//返回数组容量
int getcapacity()
{
return this->m_capacity;
}
//返回数组的大小
int getSize()
{
return this->m_size;
}
private:
T* pAddress;//指针指向堆区开辟的真实数组
int m_size;//数组容量
int m_capacity;//数组大小
};
test.cpp
#include<iostream>
#include<string>
using namespace std;
#include"myArray.hpp"
void printintArray(MyArray<int>& arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout << arr[i] << endl;
}
}
void test01()
{
MyArray<int>arr1(5);
for (int i = 0; i < 5; i++)
{
arr1.PushBack(i);
}
cout << "arr1打印输出为" << endl;
printintArray(arr1);
cout<<"arr1容量为:"<<arr1.getcapacity()<<endl;
cout << "arr1大小为:" << arr1.getSize() << endl;
cout << endl;
cout << "arr2打印输出为" << endl;
MyArray<int>arr2(arr1);//拷贝构造
arr2.PopBack();
printintArray(arr2);
cout << "arr2容量为:" << arr2.getcapacity() << endl;
cout << "arr2大小为:" << arr2.getSize() << endl;
}
class Person
{
public:
Person(){};
Person(string name,int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void printPersonarr(MyArray<Person>&arr)
{
for (int i = 0; i < arr.getSize(); i++)
{
cout <<"姓名: " <<arr[i].m_name<<endl;
cout << "年龄: " << arr[i].m_age << endl;
}
}
void test02()
{//开辟10个空间
MyArray<Person>arr(10);
//创建4个数据
Person p1("孙悟空", 999);
Person p2("孙悟空", 999);
Person p3("孙悟空", 999);
Person p4("孙悟空", 999);
//插入数据
arr.PushBack(p1);
arr.PushBack(p2);
arr.PushBack(p3);
arr.PushBack(p4);
printPersonarr(arr);
cout << "arr容量为:" << arr.getcapacity() << endl;
cout << "arr大小为:" << arr.getSize() << endl;
}
int main()
{
//test01();
test02();
}