//MyArray.hpp:
#pragma once
#include<iostream>
using namespace std;
#include<string>
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()//析构函数
{
cout << "析构函数调用" << endl;
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->m_capacity=0;
this->m_size = 0;
}
}
MyArray(const MyArray& a1)
{
cout << "拷贝函数调用" << endl;
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
this->m_capacity = a1.m_capacity;
this->m_size = a1.m_size;
this->pAddress = new T[a1.m_capacity];
for (int i = 0; i < a1.m_size; i++)//深度拷贝
{
this->pAddress[i] = a1.pAddress[i];
}
}
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 << "数组为空" << endl;
return;
}
this->m_size--;
}
int GetSize()
{
return this->m_size;
}
int GetCapacity()
{
return this->m_capacity;
}
T& operator[](int p)//
{
if (this->m_size <= p)
{
cout << "该位置无数据" << endl;
}
return this->pAddress[p];
}
MyArray& operator=(const MyArray& a1)//重载=
{
cout << "operator=调用" << endl;
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
this->m_capacity = a1.m_capacity;
this->m_size = a1.m_size;
this->pAddress = new T[a1.m_capacity];
for (int i = 0; i < a1.m_size; i++)
{
this->pAddress[i] = a1.pAddress[i];
}
return *this;
}
private:
T* pAddress;
int m_capacity;
int m_size;
};
//mian.cpp:
#include"MyArray.hpp"
void show(MyArray<int> & arr)
{
for (int i = 0; i < arr.GetSize(); i++)
{
cout << arr[i] << " ";
}
cout << 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 showPerson(MyArray<Person>& arr)
{
for (int i = 0; i < arr.GetSize(); i++)
{
cout << arr[i].m_name << " " << arr[i].m_age << endl;;
}
}
void test()
{
Person p1("张三", 20);
Person p2("李四", 20);
Person p3("王五", 20);
Person p4("赵六", 20);
Person p5("Tom", 20);
MyArray<Person> arr1(5);
arr1.Push_Back(p1);
arr1.Push_Back(p2);
arr1.Push_Back(p3);
arr1.Push_Back(p4);
arr1.Push_Back(p5);
showPerson(arr1);
cout << "数组容量:" << arr1.GetCapacity() << endl;
cout << "数组有效量:" << arr1.GetSize() << endl;
arr1.Pop_Back();
cout << "数组有效量:" << arr1.GetSize() << endl;
}
int main()
{
test();
return 0;
}