黑马程序员C++学习代码: 题目: 写一个自定义的数组泛型类,可以实现int、char和自定义类型等的数组,实现数组的尾插、尾删、将一个数组赋值给另一个数组等功能
代码:
myArray泛型类:
#pragma once
#pragma once
#include<iostream>
using namespace std;
template<class T>
class myArray {
public:
myArray(int capcity) {//构造函数
this->m_Capcity = capcity;
this->m_Size = 0;
this->m_pAddress = new T[this->m_Capcity];
}
//拷贝构造
myArray(const myArray& arr) {
this->m_Capcity = arr.m_Capcity;
this->m_Size = arr.m_Size;
//this->m_pAddress = arr->m_Size;这个是浅拷贝,我们要做深拷贝,即开辟新的内存空间
//深拷贝
this->m_pAddress = new T[arr.m_Capcity];
if (arr.m_pAddress != NULL) {//如果数组arr中有数据,也要拷贝过来
for (int i = 0; i < arr.m_Size; i++) {
this->m_pAddress[i] = arr.m_pAddress[i];
}
}
}
//重载=,防止浅拷贝问题
myArray& operator=(const myArray& arr) {
//若原来数组有数据要先释放
if (this->m_pAddress != NULL) {
delete[] this->m_pAddress;
this->m_pAddress = NULL;
this->m_Capcity = 0;
this->m_Size = 0;
}
this->m_Capcity = arr.m_Capcity;
this->m_Size = arr.m_Size;
this->m_pAddress = new T[arr.m_Capcity];
if (arr.m_pAddress != NULL) {
for (int i = 0; i < this->m_Size; i++) {
this->m_pAddress[i] = arr.m_pAddress[i];
}
}
return *this;
}
//尾插法
void Push_Back(const T& value) {
if (this->m_Size == this->m_Capcity) {
cout << "数组已满,无法插入" << endl;
return;
}
this->m_pAddress[this->m_Size] = value;
this->m_Size++;
}
//尾删除
void Pop_Back() {
if (this->m_Size == 0) {
cout << "数组已经为空,删除失败" << endl;
return;
}
this->m_Size--;//逻辑上让数组数量大小-1,即访问不到这个元素,实现尾删
}
//通过下标访问数据
T& operator[](int index) {
return this->m_pAddress[index];
}
//返回数组容量
int getCapcity() {
return this->m_Capcity;
}
//返回数组元素数量
int getSize() {
return this->m_Size;
}
~myArray() {//析构函数
if (this->m_pAddress != NULL) {
delete[] this->m_pAddress;
this->m_pAddress = NULL;
}
}
private:
T* m_pAddress;//指向数组的指针
int m_Size;//数组中的元素个数
int m_Capcity;//数组的容量
};
主函数:
#include<iostream>
#include "myArray.hpp"
using namespace std;
void printArray(myArray<int> arr) {
for (int i = 0; i < arr.getSize(); i++) {
cout << arr[i] << endl;
}
}
void test1() {
myArray<int> arr1(5);
for (int i = 0; i < 5; i++) {
arr1.Push_Back(i);
}
cout << "测试数组的元素输出" << endl;
printArray(arr1);
cout << endl << endl << "测试数组arr1的大小size输出" << endl;
cout << arr1.getSize()<<endl;
cout << "测试数组arr1的大小capcity输出" << endl;
cout << arr1.getCapcity() << endl;
arr1.Pop_Back();
cout << "测试数组arr1尾删后arr1的大小size输出" << endl;
cout << arr1.getSize() << endl;
cout <<"测试数组arr1尾删后的大小capcity输出" << endl;
cout << arr1.getCapcity() << endl;
cout << "-------------------------------------------------------------" << endl;
myArray<int>arr2(5);
arr2.operator=(arr1);
cout << "调用arr2.operator=(arr1)后arrr2的数组元素输出" << endl;
printArray(arr2);
cout << "测试数组arr2的大小size输出" << endl;
cout << arr2.getSize() << endl;
cout << "测试数组arr2的大小capcity输出" << endl;
cout << arr2.getCapcity() << endl;
}
int main() {
test1();
}
运行结果截图: