c++实现任意类型数组类的封装
生活随笔
收集整理的這篇文章主要介紹了
c++实现任意类型数组类的封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
MyArray.hpp
#pragma once #include<iostream> #include<string> using namespace std; template<class T>class MyArray { public://構造explicit MyArray(int capacity) //防止隱式類型轉換,防止MyArray arr =10{this->m_Capacity = capacity;this->m_Size = 0;this->pAddress = new T[this -> m_Capacity];}MyArray(const MyArray &array){this->m_Capacity = array.m_Capacity;this->m_Size = array.m_Size;this->pAddress = new T[this->m_Capacity];for (int i = 0; i < m_Size; i++){this->pAddress[i] = array[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 = array.m_Capacity;this->m_Size = array.m_Size;this->pAddress = new T[this->m_Capacity];for (int i = 0; i < m_Size; i++){this->pAddress[i] = array[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 m_Size;}//獲取容量int getCapacity(){return m_Capacity;}private:T * pAddress; //指向堆區指針int m_Capacity; //容量int m_Size; };test.cpp
#include"MyArray.hpp" #include<string> #include<iostream> using namespace std; //輸出int 類型數組 void printIntArray(MyArray<int>&array) {for (int i = 0; i < array.getSize(); i++){cout << array[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 printPersonArray(MyArray<Person > &array) {for (int i = 0; i < array.getSize(); i++){cout << "姓名:" << array[i].m_Name << "年齡:" << array[i].m_Age << endl;} }int main() {MyArray<int>arr(10);for (int i = 0; i < 10; i++){arr.push_Back(i + 100);}printIntArray(arr);Person p1("MT", 10);Person p2("呆賊", 12);Person p3("傻饃", 13);Person p4("劣人", 14);MyArray<Person>arr2(10);arr2.push_Back(p1);arr2.push_Back(p2);arr2.push_Back(p3);arr2.push_Back(p4);printPersonArray(arr2);system("pause");return 0; }總結
以上是生活随笔為你收集整理的c++实现任意类型数组类的封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做试管婴儿能上班吗
- 下一篇: 成都大熊猫繁育基地网上票买完了现场可以买