.hpp文件
#pragma
#include<iostream>
using namespace std;
template<class T>
class My_arry
{
public:
My_arry(int capacity)//赋初值
{
this->m_capacity = capacity;//容量
this->m_Arry_size = 0;//大小
this->m_Arry_Addres = new T[capacity];
}
My_arry(const My_arry &arr)//拷贝函数的深拷贝//arr1(arr2)
{
this->m_capacity = arr.m_capacity;
this->m_Arry_size = arr.m_Arry_size;
this->m_Arry_Addres = new T[arr.m_capacity];
for (int i = 0; i < arr.m_Arry_size; i++)
{
this->m_Arry_Addres[i] = arr.m_Arry_Addres[i];
}
}
My_arry& operator=(const My_arry& arr)//=运算符重载//arr1=arr2
{
if (this->m_Arry_Addres != NULL)//先将自身属性删除
{
delete[] this->m_Arry_Addres;
this->m_Arry_Addres = NULL;
this->m_Arry_size = 0;
this->m_capacity = 0;
}
//然后进行深拷贝
this->m_capacity = arr.m_capacity;
this->m_Arry_size = arr.m_Arry_size;
this->m_Arry_Addres = new T[arr.m_capacity];
for (int i = 0; i < arr.m_Arry_size; i++)
{
this->m_Arry_Addres[i] = arr.m_Arry_Addres[i];
}
return *this;
}
//尾插法
void Push_Back(const T val)
{
if (this->m_capacity == this->m_Arry_size)
{
cout << "数组已满" << endl;
return;
}
this->m_Arry_Addres[this->m_Arry_size] = val;
this->m_Arry_size++;//加完人后,数组大小++
}
//尾删除
void Pop_Back()
{
if (this->m_Arry_size == 0)
{
cout << "数组为空" << endl;
return;
}
this->m_Arry_size--;//逻辑删除,实际还是存在数据,可以用指定数字访问到
}
T& operator[](int index)//[]运算符重载,返回本身用T&
{
return this->m_Arry_Addres[index];
}
int Get_capacity()//获取数组容积
{
return this->m_capacity;
}
int Get_size()//获取数组大小
{
return this->m_Arry_size;
}
~My_arry()
{
if (this->m_Arry_Addres != NULL)
{
delete[] this->m_Arry_Addres;
this->m_Arry_Addres = NULL;
}
}
T* m_Arry_Addres;
int m_capacity;
int m_Arry_size;
};
.cpp文件
#include<iostream>
#include<string>
#include"classarry.hpp"
using namespace std;
void Print_arry(My_arry<int>&p)//打印内置类型数据的数组
{
for (int i = 0; i < p.m_Arry_size; i++)
{
cout <<p[i]<< endl;
}
}
class Person
{
public:
Person() {};//这步不能少,不然this->m_Arry_Addres = new T[capacity];不能创建内存空间
Person(string name,int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void test01()//测试存储内置类型数据的数组
{
My_arry<int>arr1(5);
for (int i = 0; i < arr1.m_capacity; i++)
{
arr1.Push_Back(i);
}
Print_arry(arr1);
}
void Print_Person(My_arry<Person>& p)//写在Person类后,写在前面要声明类
{
for (int i = 0; i < p.Get_size(); i++)
{
cout << "姓名:" << p[i].m_name << " 年龄:" << p[i].m_age << endl;
}
}
void test02()//测试存储自定义类型数据的数组
{
Person p1("张三", 20);
Person p2("李四", 15);
Person p3("王五", 18);
My_arry<Person>arr1(3);
arr1.Push_Back(p1);
arr1.Push_Back(p2);
arr1.Push_Back(p3);
Print_Person(arr1);
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
标签:arr,封装,Addres,int,vector,模板,capacity,Arry,size
From: https://blog.csdn.net/weixin_74207910/article/details/140463689