案例中用到的方法
- 可以对内置数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据类型存储到堆区
- 构造函数中可以传入数组的容量
- 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
- 提供尾插法和尾删法对数组中的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获取数组中当前元素个数和数组的容量
·myarray.hpp头文件
#define _CRT_SECURE_NO_DEPRECATE
#pragma once
#include<iostream>using namespace std;template<class T>
class Myarray
{
public://构造函数Myarray(int capacity){this->m_capacity = capacity;this->m_size = 0;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[this->m_capacity];for (int i = 0; i < this->m_size; i++){//如果T为对象,而且还包括指针,必须需要重载 = 操作符 ,因为这个等号不是 构造 而是赋值//普通类型可以 = 但是指针类型需要深拷贝this->paddress[i] = arr.paddress[i];}}//重载 = 操作符 防止浅拷贝问题Myarray& operator=(const Myarray& myarray){if (this->paddress != NULL){delete[] this->paddress;this->m_capacity = 0;this->m_size = 0;}this->m_capacity = myarray.m_capacity;this->m_size = myarray.m_size;this->paddress = new T[this->m_capacity];for (int i = 0; i < this->m_size; i++){this->paddress[i] = myarray[i];}return *this;}//重载 [] 操作符 arr[0]T& operator [](int index){return this->paddress[index]; //不考虑跨界,用户自己去处理}//尾插法void Push_back(const T& val){if (this->m_capacity == this->m_size){return;}this->paddress[this->m_size] = val;this->m_size++;}//尾删法void Pop_back(){if (this->m_size == 0){return;}this->m_size--;}//获取数组容量int getCapacity(){return this->m_capacity;}//获取数组大小int getSize(){return this->m_size;}//析构~Myarray(){if (this->paddress != NULL){delete[] this->paddress;this->paddress = NULL;this->m_capacity = 0;this->m_size = 0;}}private:T* paddress; //指向一个堆空间,这个空间存储真正的数据int m_capacity; //容量int m_size; //大小
};
·主函数
#include<iostream>
using namespace std;
#include<string>
#include "myarray.hpp"void printintarray(Myarray<int>& arr) //参数是拷贝构造函数
{for (int i = 0; i < arr.getSize(); i++) {cout << arr[i] << " ";}cout << endl;
}//测试内置数据类型
void test01()
{Myarray<int> array1(10);for (int i = 0; i < 10; i++){array1.Push_back(i);}cout << "array1打印输出:" << endl;printintarray(array1);cout << "array1的大小: " << array1.getSize() << endl;cout << "array1的容量: " << array1.getCapacity() << endl;}//测试自定义数据类型
class Person {
public://Person() {};必须添加默认的构造函数,可能因为在创建数组的时候还需要传参//Person() {};Person(string name, int age){this->mname = name;this->mage = age;}
public:string mname;int mage;
};void printpersonintarray(Myarray<Person>& arrperson) //参数是拷贝构造函数
{for (int i = 0; i < arrperson.getSize(); i++) {cout <<"姓名:" << arrperson[i].mname << "年龄 :"<<arrperson[i].mage;}cout << endl;
}void test02()
{//如果在定义构造函数时候没有写默认构造函数Person() {}// 则在编译类模板成员函数 Myarray<Person>::Myarray(int)时//创建数组Myarray<Person> parray(10); //Person p1("hg", 20);Person p2("hg", 20);Person p3("hg", 20);Person p4("hg", 20);parray.Push_back(p1);parray.Push_back(p2);parray.Push_back(p3);parray.Push_back(p4);printpersonintarray(parray);cout << "parray的大小" << parray.getSize() << endl;cout << "parray的容量" << parray.getCapacity() << endl;}int main()
{test01();test02();return 0;
}