c++之类模板案例
发布时间:2020-12-16 09:06:33 所属栏目:百科 来源:网络整理
导读:描述:使用一个通用的数组类,要求如下: 1.可以对内置数据类型以及自定义数据类型进行存储; 2.将数组中的数据存储到堆区; 3.构造函数中可以传入数组的容量; 4.提供对应的拷贝函数以及operator=防止浅拷贝问题; 5.提供尾插法和尾删法对数组中的元素进行
描述:使用一个通用的数组类,要求如下: 1.可以对内置数据类型以及自定义数据类型进行存储; 2.将数组中的数据存储到堆区; 3.构造函数中可以传入数组的容量; 4.提供对应的拷贝函数以及operator=防止浅拷贝问题; 5.提供尾插法和尾删法对数组中的元素进行增加和删除; 6.可通过下标进行访问数组中的元素; 7.可以获得数组中当前元素的个数以及容量; 头文件:MyArray.hpp #include<iostream> using namespace std; template<class T> class MyArray { public: //有参构造 MyArray(int capacity) { cout << "有参构造函数调用" << endl; this->m_Capacity = capacity; this->m_Size = 0; this->pAddress = new T[this->m_Capacity]; } 析构函数 ~MyArray() { cout << 析构函数调用if (this->pAddress != NULL) { delete[] pAddress; this->pAddress = NULL; } } 拷贝构造 MyArray(const MyArray& arr) { cout << 拷贝构造函数调用 arr.m_Capacity; this->m_Size = arr.m_Size; this->pAddress = arr.pAddress; 深拷贝 new T[arr.m_Capacity]; 还要将原有数据拷贝过来 for (int i = 0; i < this->m_Size; i++) { this->pAddress[i] = arr.pAddress[i]; } } operator=也是为了防止浅拷贝问题 MyArray& operator=(重载=调用先判断原来的堆区是否有数据,如果有先释放 NULL; ; this->m_Capacity = ; } arr.pAddress[i]; } return *this; } 尾插法插入数据 void Push_Back(const T& val) { this->m_Capacity == m_Size) { returnthis->pAddress[this->m_Size] = val; this->m_Size++尾删法 void Pop_back() { this->m_Size == this->m_Size--通过数组下标访问数据 T& operator[]( index) { return pAddress[index]; } 返回数组的容量 getCapacity() { m_Capacity; } 返回数组的大小 getSize() { m_Size; } private: T* pAddress;指针指向堆区开辟的真实数组 int m_Capacity;容量 int m_Size;数组大小 }; 源文件:test.cpp #include myArray.hpp" void printArr(MyArray <int>& arr) { 0; i < arr.getSize(); i++) { cout << arr[i] << " "; } cout << endl; } test() { MyArray <int>arr1(5); MyArray <int>arr2(arr1); MyArray <int>arr3(10); arr3 = arr1; 插入数据 arr1.Push_Back(1); arr1.Push_Back(2); cout << 插入之后的数组: endl; printArr(arr1); cout << 删除最后一个元素的数组: endl; arr1.Pop_back(); printArr(arr1); cout << 此时数组的大小:" << arr1.getSize()<<endl; cout << 此时数组的容量:" << arr1.getCapacity() << endl; } main() { test(); system(pausereturn ; } 运行结果: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |