myArray.hpp
#pragma once
#include<iostream>
using namespace std;
#include<string>
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(const MyArray& arr)
{
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];
}
}
//是为了输出自定义的数据类型
MyArray& operator=(const MyArray & arr)//运算符重载,防止浅拷贝的问题
{
//如果堆区有数据先释放
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->m_Size = 0;
this->m_Capacity = 0;
}
//深拷贝
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
this->pAddress = new T[this->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 << "无了" << endl;
return;
}
this->m_Size--;
}
//通过下标访问元素 重载[]
T& operator[](int index)
{
return this->pAddress[index];
}
int get_Capacity()
{
return this->m_Capacity;
}
int get_Size()
{
return this->m_Size;
}
~MyArray()
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
private:
T * pAddress;//指针指向堆区开辟的真实空间
int m_Capacity;
int m_Size;
};
main.c
#include"MyArray.hpp"
void printArray1(MyArray<int> &arr)
{
for (int i = 0; i < arr.get_Size(); i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void test1()//原有的数据类型
{
//arr
MyArray<int>arr(5);
for (int i = 0; i < 5; i++)
{
arr.Push_Back(i);
}
printArray1(arr);
cout << "arr的容量: " << arr.get_Capacity() << endl;
cout << "arr的大小: " << arr.get_Size() << endl;
cout << endl;
//arr1
MyArray<int>arr1(arr);
printArray1(arr);
arr.Pop_Back();
printArray1(arr);
cout << "arr的容量: " << arr.get_Capacity() << endl;
cout << "arr的大小: " << arr.get_Size() << endl;
}
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
void printArray2(MyArray <Person> &arr2)
{
for (int i = 0; i < arr2.get_Size(); i++)
{
cout << arr2[i].m_Name<<": "<<arr2[i].m_Age << endl;
}
}
void test2()//自定义数据类型
{
MyArray<Person>arr2(10);
Person p1("张三", 18);
Person p2("张四", 28);
Person p3("张五", 38);
Person p4("张六", 48);
Person p5("张七", 58);
arr2.Push_Back(p1);
arr2.Push_Back(p2);
arr2.Push_Back(p3);
arr2.Push_Back(p4);
arr2.Push_Back(p5);
printArray2(arr2);
cout << "arr的容量: " << arr2.get_Capacity() << endl;
cout << "arr的大小: " << arr2.get_Size() << endl;
}
int main()
{
//test1();
test2();
system("pause");
return 0;
}