// ============================================================================ // p1c05_12 — 5.8 类模板的应用 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; #include // --- 原文片段 [58954472:11] 5.8 类模板的应用 --- #include using std::string; template class MyArray { public: explicit MyArray(int capacity) { this->m_Capacity = capacity; this->m_Size = 0; // 如果T是对象,那么这个对象必须提供默认的构造函数 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++) { this->pAddress[i] = arr.pAddress[i]; } } 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) this->m_Size--; } 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; }; class Person { public: Person() {} Person(string name, int age) { this->mName = name; this->mAge = age; } public: string mName; int mAge; }; void PrintMyArrayInt(MyArray& arr) { for (int i = 0; i < arr.getSize(); i++) { cout << arr[i] << " "; } cout << endl; } void PrintMyPerson(MyArray& personArr) { for (int i = 0; i < personArr.getSize(); i++) { cout << "姓名:" << personArr[i].mName << " 年龄:" << personArr[i].mAge << endl; } } // --- 测试代码(原文为文件作用域裸语句,已包进 main 使其可编译运行)--- int main() { MyArray myArrayInt(10); for (int i = 0; i < 9; i++) { myArrayInt.Push_back(i); } myArrayInt.Push_back(100); PrintMyArrayInt(myArrayInt); MyArray myArrayPerson(10); Person p1("德玛西亚", 30); Person p2("提莫", 20); Person p3("孙悟空", 18); Person p4("赵信", 15); Person p5("赵云", 24); myArrayPerson.Push_back(p1); myArrayPerson.Push_back(p2); myArrayPerson.Push_back(p3); myArrayPerson.Push_back(p4); myArrayPerson.Push_back(p5); PrintMyPerson(myArrayPerson); return 0; } // --- main ---