//模板初识 //myArray.hpp: //myArray #pragma once template<class T1> class MyArray { public: //有参构造的实现 MyArray(int capacity) { //cout << "myarray有参构造函数运行" << endl; this->m_Capacity = capacity; this->m_Size = 0; this->pAddress = new T1[this->m_Capacity]; } //拷贝构造函数的实现 MyArray(const MyArray& myarray) { //cout << "myarray拷贝构造函数运行" << endl; this->m_Capacity = myarray.m_Capacity; this->m_Size = myarray.m_Size; this->pAddress = new T1[this->m_Capacity]; for (int i = 0; i < this->m_Capacity; i++) { this->pAddress[i] = myarray.pAddress[i]; } } MyArray& operator=(const MyArray& myarray) { //cout << "myarray的operator=构造函数运行" << endl; if (myarray.pAddress != NULL) { delete[] this->pAddress; this->pAddress = NULL; } this->m_Capacity = myarray.m_Capacity; this->m_Size = myarray.m_Size; this->pAddress = new T1[this->m_Capacity]; for (int i = 0; i < this->m_Capacity; i++) { this->pAddress[i] = myarray.pAddress[i]; } return *this; } ~MyArray() { //cout << "myarray析构函数运行" << endl; if (this->pAddress != NULL) { delete[] this->pAddress; this->pAddress = NULL; } } int getSize() { return this->m_Size; } void AddEnd(T1 t) { if (this->m_Size == this->m_Capacity) { return; } this->pAddress[this->m_Size] = t; this->m_Size++; } void DelEnd() { if (this->m_Size == 0) { return; } this->m_Size--; } T1& operator[](int idex) { return this->pAddress[idex]; } private: T1* pAddress; int m_Capacity; int m_Size; }; //Main: //main.h #include<iostream> using namespace std; #include<string> #include"myArray.hpp" //创建自定义数据类型 class Person { public: Person() {} Person(string name, int age) { this->m_Name = name; this->m_Age = age; } int m_Age; string m_Name; }; void printfMyArray(MyArray<int> arr) { for (int i = 0; i < arr.getSize(); i++) { cout << arr[i] << endl; } } void printfMyArray1(MyArray<Person> arr) { for (int i = 0; i < arr.getSize(); i++) { cout << arr[i].m_Name << arr[i].m_Age << endl; } } //系统内置数据类型的数组测试 void test01() { MyArray<int> t(5); MyArray<int> a(t); MyArray<int> c(20); for (int i = 0; i < 5; i++) { t.AddEnd(i); } t[1] = 100; cout << "输入t" << endl; printfMyArray(t); t.DelEnd(); cout << "输出删除一个数据后的t" << endl; printfMyArray(t); } //自定义数据类型形的测试 void test02() { Person p1("张三", 20); Person p2("李四", 30); Person p3("王五", 80); Person p4("赵六", 21); Person p5("老八", 76); MyArray<Person> arr(10); arr.AddEnd(p1); arr.AddEnd(p2); arr.AddEnd(p3); arr.AddEnd(p4); arr.AddEnd(p5); printfMyArray1(arr); } int main() { test01(); test02(); return 0; }
利用模板创建多功能数组MyArray
于 2023-05-31 16:30:47 首次发布