C++-------模板類案例:利用類模板寫一個數組類
阿新 • • 發佈:2019-01-13
#pragma once #include <iostream> #include <string> using namespace std; template<class T> class MyArry { public: //建構函式: explicit MyArry(int capacity) //防止隱式型別轉換,避免:MyArry arr =10 ;這種寫法; { this->m_Capacity = capacity; this->m_Size = 0; this->Address = new T[this->m_Capacity]; } //拷貝構造: MyArry(const MyArry & arry) { this->m_Capacity = arry.m_Capacity; this->m_Size = arry.m_Size; this->Address = new MyArry[this->m_Capacity]; for (int i = 0; i < arry.m_Size; i++) { this->Address[i] = arry[i]; } } //解構函式: MyArry() { if (this->Address != NULL) { delete[] this->Address; this->Address = NULL; } } //過載一個=操作符: MyArry & operator =(const MyArry & arr) { if (this->Address != NULL) { delete[] this->Address; this->Address = NULL; } this->m_Capacity = arr.m_Capacity; this->m_Size = arr.m_Size; this->Address = new MyArry[this->m_Capacity]; for (int i = 0; i < arr.m_Size; i++) { this->Address[i] = arr[i]; } } //過載一個[]用於索引: T & operator[](int index) { return this->Address[index]; } //尾插法: void push_Back(T val) { this->Address[this->m_Size] = val; this->m_Size++; } //獲取大小: int getSize(MyArry & arr) { return this->m_Size; } //獲取容量: int getCapacity(MyArry & arr) { return this->m_Capacity; } private: T * Address; //指向堆區空間; int m_Capacity; //容量大小; int m_Size; //大小; };
main.cpp:
// 19_1_13_study.cpp : 此檔案包含 "main" 函式。程式執行將在此處開始並結束。 // #include "pch.h" #include "MyArry.hpp" #include <iostream> #include <string> using namespace std; //輸出int型陣列的方法: void printIntArry(MyArry<int> & arr) { int i = 0; for (i; i < arr.getSize(arr); i++) { cout << arr[i] << endl; } } class Person { public: Person(){} Person(string name,int age) { this->m_Name = name; this->m_Age = age; } string m_Name; int m_Age; }; //Person類輸出函式: void printPersonArry(MyArry<Person> & arry) { int i = 0; for (i; i < arry.getSize(arry); i++) { cout << "姓名:"<<arry[i].m_Name<<" 年齡:"<<arry[i].m_Age << endl; } } int main() { MyArry<int> arry(10); for (int i = 0; i < 10; i++) { arry.push_Back(i); } printIntArry(arry); Person p1("asdasd", 123); Person p2("sd", 12343); Person p3("asdasdfsd", 23423); Person p4("asfdsad", 23423); MyArry<Person> pArry(4); //自定義的預設Person型別的陣列的時候,一定會呼叫Person的預設構造的; pArry.push_Back(p1); pArry.push_Back(p2); pArry.push_Back(p3); pArry.push_Back(p4); printPersonArry(pArry); return 0; }
模板類