38.1 myArray.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
#include
class MyArray
{
public:
MyArray(); // 默认构造
MyArray(int capacity); // 有参构造 用户指定容量
MyArray(const MyArray & arr); // 拷贝构造
void pushBack(int val); // 尾插
void setData(int pos, int val); // 按位置更改数值
int getData(int pos); // 根据位置获取数据
int getCapaity(); // 获取容量
int getSize(); // 获取数组大小
int& operator[](int pos); // 重载[]
~MyArray(); // 析构函数
private:
int * p; // 数组首地址
int m_Capacity; // 数组容量
int m_Size; // 数组实际长度
};
38.2 myArray.cpp
#include"myArray.h"
MyArray::MyArray() // 默认构造
{
this->m_Capacity = 100;
this->m_Size = 0;
this->p = new int[this->m_Capacity];
}
MyArray::MyArray(int capacity) // 有参构造 用户指定容量
{
this->m_Capacity = capacity;
this->m_Size = 0;
this->p = new int[this->m_Capacity];
}
MyArray::MyArray(const MyArray & arr) // 拷贝构造
{
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size; //深拷贝 先开辟空间在拷贝
this->p = new int[arr.m_Capacity];
for (int i = 0;i < arr.m_Size;i++)
{
this->p[i] = arr.p[i];
}
}// 尾插
void MyArray::pushBack(int val)
{
this->p[this->m_Size] = val; // 尾插值
this->m_Size++; // 更新值
}// 按位置更改数值
void MyArray::setData(int pos, int val)
{
this->p[pos] = val;
}// 根据位置获取数据
int MyArray::getData(int pos)
{
return this->p[pos];
}// 获取容量
int MyArray::getCapaity()
{
return this->m_Capacity;
}// 获取数组大小
int MyArray::getSize()
{
return this->m_Size;
}
// 重载[]
int& MyArray::operator[](int pos)
{
return this->p[pos];
}
MyArray::~MyArray() // 析构函数
{
if (this->p != NULL)
{
delete[] this->p;
this->p = NULL;
}
}
38.3 test.cpp
#include"myArray.h"
int main()
{
MyArray arr1; //测试各种构造
MyArray arr2(200);
MyArray arr3(arr2);
// 获得容量和大小
cout << "arr1的容量: " << arr1.getCapaity() << " arr1的大小: " << arr1.getSize() << endl;
cout << "arr2的容量: " << arr2.getCapaity() << " arr2的大小: " << arr2.getSize() << endl;
cout << "arr3的容量: " << arr3.getCapaity() << " arr3的大小: " << arr3.getSize() << endl;
arr1.pushBack(10); // 尾插
arr1.pushBack(20);
arr1.pushBack(30);
arr1.pushBack(40);
arr1.pushBack(50);
for (int i = 0;i < arr1.getSize();i++) // 按位置获得数据
{
cout << arr1.getData(i) << endl;
}
cout << "arr1的容量: " << arr1.getCapaity() << " arr1的大小: " << arr1.getSize() << endl;
arr1.setData(0, 1000); // 按位置修改数据
cout << "0号位置的数值: " << arr1.getData(0) << endl;
arr1[1] = 123; // 测试[]重载
cout << "重载后: " << arr1.getData(1) << endl;
}
![836d589f49a78caeb0033248cf452dc2.png](https://i-blog.csdnimg.cn/blog_migrate/980a31cdac3dc5a9a6e8b7f944897d7b.jpeg)