C++数组类封装

454 阅读2分钟

一、MyArray.h

  #pragma once
 #include<iostream>
 using namespace std;
 
 class MyArray
 {
 public:
 	//默认
 	MyArray();
 	//有参
 	MyArray(int capacity);
 	//拷贝
 	MyArray(const MyArray & arr);
 
 	//尾插
 	void pushBack(int val);
 	//根据位置设置数据
 	void setData(int inder, int val);
 	//根据位置获取数据
 	int getData(int index);
 	//获取数组大小
 	int getSize();
 	//获取数组容量
 	int getCapacity();
 	//析构
 	~MyArray();
 private:
 	//指向堆区的数据指针
 	int * pAddress;
 	//数组容量
 	int m_Capacity;
 	//数组大小
 	int m_Size;
 };

二、文件封装

 #include"MyArray.h"
 
 MyArray::MyArray()
 {
 	cout << "默认构造函数调用" << endl;
 	this->m_Capacity = 100;
 	this->m_Size = 0;
 	this->pAddress = new int[this->m_Capacity];
 }
 
 MyArray::MyArray(int capacity)
 {
 	cout << "有参构造函数调用" << endl;
 	this->m_Capacity = capacity;
 this->m_Size = 0;
 	this->pAddress = new int[this->m_Capacity];
 }
 
 MyArray::MyArray(const MyArray & arr)
 {
 	cout << "拷贝构造函数调用" << endl;
 	this->m_Size = arr.m_Size;
 	this->m_Capacity = arr.m_Capacity;
 	this->pAddress = new int[this->m_Capacity];
 
 	for (int i = 0; i < m_Size; i++)
 	{
	this->pAddress[i] = arr.pAddress[i];
 	}
 }
 
  
 void MyArray::pushBack(int val)
 {
 	this->pAddress[this->m_Size] = val;
 	this->m_Size++;
 }
 
 void MyArray::setData(int index, int val)
 {
 	this->pAddress[index] = val;
 }
 	
 int MyArray::getData(int index)
 {
 	return this->pAddress[index];
 }
 
 int MyArray::getSize()
 {
	return this->m_Size;
 }
 
 int MyArray::getCapacity()
 {
	return this->m_Capacity;
 }
 
 MyArray::~MyArray()
 {
	cout << "析构函数调用" << endl;
	if (this->pAddress != NULL)
	{
		delete[]this->pAddress;
		this->pAddress = NULL;
	}
 }
 
 
 int * pAddress;
 
 int m_Capacity;
 
 int m_Size;

三、封装实现

 #include<iostream>
 using namespace std;
 #include"myarry.h"
 
 void test01()
 {
 	MyArray * arr = new MyArray(10);
 	delete arr; //堆区
 
 	MyArray arr2;
 	for (int i = 0; i < 10; i++)
 	{
	arr2.pushBack(i + 100);
 	}
 	MyArray arr3(arr2);
 	//测试设置数据 
 	arr3.setData(0,1000);
 	for (int i = 0; i < 10; i++)
 	{
 		cout << "位置为" << i + 1 << "的元素为:" << arr3.getData(i) << endl;
 	}
 	cout << "数组的容量为: " << arr3.getCapacity() << endl;
 	cout << "数组的大小为: " << arr3.getSize() << endl;
 }
 int main()
 {
 	test01();
 	return 0;
 }

参考:

 #ifndef LEI_H_
 #define LEI_H_
 
 class MyArray
 {
 public:
 	//无参构造函数,用户没有指定容量,则初始化为100
 	MyArry();
 	//有参构造函数,用户指定容量初始化
 	explicit MyArray(int capacity);
 	//用户操作接口
 	//根据位置添加元素
 	void SetData(int pos, int val);
 	//获得指定位置数据
 	int GetData(int pos);
 	//尾插法
 	void PushBack(int val);
 	//获得长度
 	int GetLenght();
 	//析构函数,释放空间
 	~MyArray();
 private:
 	int mCapacity;//数组一共可容纳多少个元素
 	int mSize;//当前有多少个元素
 	int * pAdress;//指向储存数据的空间
 };
 #endif