日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

c++实现任意类型数组类的封装

發布時間:2023/11/30 c/c++ 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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++实现任意类型数组类的封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。