🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ template<class T> class MyArray { private: T *p; int mCapacity; int mSize; public: MyArray(int capacity) { this->mCapacity = capacity; this->mSize = 0; //T如果是Maker,这里要调用什么构造函数,要调用无参构造 p = new T[this->mCapacity]; } //拷贝构造 MyArray(const MyArray &arr) { this->mCapacity = arr.mCapacity; this->mSize = arr.mSize; p = new T[arr.mCapacity]; for (int i = 0; i < this->mSize; ++i) { p[i] = arr.p[i]; } } //赋值函数 MyArray &operator=(const MyArray &arr) { if (this->p != NULL) { delete[] this->p; this->p = NULL; } p = new T[arr.mCapacity]; this->mSize = arr.mSize; this->mCapacity = arr.mCapacity; for (int i = 0; i < this->mSize; ++i) { p[i] = arr.p[i]; } return *this; } //重载[] T &operator[](int index) { return this->p[index]; } //尾插 void Push_Back(const T &val) { if (this->mSize == this->mCapacity) { return; } this->p[this->mSize] = val; this->mSize++; } //尾删 void Pop_Back() { if (this->mSize == 0) { return; } this->mSize--; } int getSize() { return this->mSize; } ~MyArray() { if (this->p != NULL) { delete[] p; p = NULL; } } }; class Maker { public: string name; int age; public: Maker() {} Maker(string name, int age) { this->name = name; this->age = age; } }; void printMaker(MyArray<Maker> &arr) { for (int i = 0; i < arr.getSize(); ++i) { cout << "姓名: " << arr[i].name << " 年龄: " << arr[i].age << endl; } } void test02() { MyArray<Maker> myarr(4); Maker m1("悟空", 17); Maker m2("贝吉塔", 30); Maker m3("短笛", 200); Maker m4("小林", 19); myarr.Push_Back(m1); myarr.Push_Back(m2); myarr.Push_Back(m3); myarr.Push_Back(m4); printMaker(myarr); MyArray<int> myint(10); for (int i = 0; i < 10; i++) { myint.Push_Back(i + 1); } for (int i = 0; i < 10; i++) { cout << myint[i] <<" "; } cout << endl; } ~~~