test.cpp
#pragma once
#include "MyArr.hpp"
#include <string>
using namespace std;
class Person
{public:Person(){}Person(int a, string n){this->age = a;this->name = n;}int age;string name;};//输出int数组void print_int(MyArray <int>&myarr)
{for (int i = 0; i < myarr.getsize(); i++){cout << myarr[i] << endl;}
}void print_string(MyArray <string>&myarr)
{for (int i = 0; i < myarr.getsize(); i++){cout << myarr[i] << endl;}
}void print_Person(MyArray <Person>&myarr)
{for (int i = 0; i < myarr.getsize(); i++){cout << myarr[i].age << "===="<<myarr[i].name << endl;}
}void test()
{MyArray <int>myarr(10);for (int i = 0; i < 10; i++){myarr.push_back(i+10);}print_int(myarr);
}void test1()
{MyArray <string>myarr(10);for (int i = 0; i < 10; i++){myarr.push_back(to_string(i+100));}print_string(myarr);
}void test2()
{MyArray <Person>myarr(5);Person p1(1, "jkd");Person p2(2, "jkd");Person p3(3, "jkd");Person p4(4, "jkd");/*string pp = "";string pp1 = "c";string pp2 = pp + pp1;string p = "";for (int i = 0; i < myarr.getsize(); i++){pp1 = "p";pp2 = to_string(i);pp = pp1 + pp2;myarr.push_back(pp);}*/myarr.push_back(p1);myarr.push_back(p2);myarr.push_back(p3);myarr.push_back(p4);print_Person(myarr);//class 丢到最上方 否则报错
}int main()
{//test();//test1();test2();system("pause");return EXIT_SUCCESS;
}
Myarr.hpp
#pragma once
#include <iostream>
using namespace std;template<class T>
class MyArray
{
public:explicit MyArray(int capacity) //防止隐式类型转换 MyArray a = 10;{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;if (this->pAddress != NULL){delete[] this->pAddress;this->pAddress = NULL;}this->pAddress = new T[arr.m_Capacity];for (int i = 0; i < arr.m_size; i++){this->pAddress[i] = arr[i]; }}~MyArray(){if (this->pAddress != NULL){delete[] this->pAddress;this->pAddress = NULL;}}//赋值重载MyArray& operator=(MyArray & array){//先判断原始数据if (this->pAddress != NULL){delete[] this->pAddress;this->pAddress = NULL;}this->m_Capacity = arr.m_Capacity;this->m_size = arr.m_size;if (this->pAddress != NULL){delete[] this->pAddress;this->pAddress = NULL;}this->pAddress = new T[arr.m_Capacity];for (int i = 0; i < arr.m_size; i++){this->pAddress[i] = arr[i];}}//[]重载//MyArray arr(10);//arr[0] = 100;T & operator[](int index){return this->pAddress[index];}//尾插法void push_back(T val){this->pAddress[this->m_size] = val;this->m_size++;}//获取大小int getsize(){return this->m_size;}//获取容量int getCapacity(){return m_Capacity;}private:T *pAddress;//指向堆区指针int m_Capacity;//容量int m_size;
};
自定义类的类型 无法for循环插入