数组类的封装
Myarray.h
#pragma once
#include<iostream>
using namespace std;
class My_Array
{
public:
My_Array();
My_Array(int capacity);
My_Array(const My_Array & arr);
void PushBack(int val);
void setData(int index, int val);
int getData(int index);
int getSize();
int getCapacity();
~My_Array();
private:
int *pAdress;
int m_Capacity;
int m_Size;
};
Myarray.cpp
#include "Myarray.h"
My_Array::My_Array()
{
this->m_Capacity = 100;
this->m_Size = 0;
this->pAdress = new int[this->m_Capacity];
}
My_Array::My_Array(int capacity)
{
this->m_Capacity = capacity;
this->m_Size = 0;
this->pAdress = new int[this->m_Capacity];
}
My_Array::My_Array(const My_Array & arr)
{
this->m_Size = arr.m_Size;
this->m_Capacity = arr.m_Capacity;
this->pAdress = new int[this->m_Capacity];
for (int i = 0; i < m_Size; i++)
{
this->pAdress[i] = arr.pAdress[i];
}
}
void My_Array::PushBack(int val)
{
this->pAdress[this->m_Size] = val;
this->m_Size++;
}
void My_Array::setData(int index, int val)
{
this->pAdress[index] = val;
}
int My_Array::getData(int index)
{
return this->pAdress[index];
}
int My_Array::getSize()
{
return this->m_Size;
}
int My_Array::getCapacity()
{
return this->m_Capacity;
}
My_Array::~My_Array()
{
if (this->pAdress != NULL)
{
delete[] this->pAdress;
this->pAdress = NULL;
}
}
1.cpp
#include<iostream>
using namespace std;
#include "Myarray.h"
void test01()
{
My_Array *arr = new My_Array(10);
delete arr;
My_Array arr2;
for (int i = 0; i < 10; i++)
{
arr2.PushBack(i + 100);
}
My_Array arr3(arr2);
for (int i = 0; i < 10; i++)
{
cout << "位置为" << i + 1 << "的元素为" << arr3.getData(i) << endl;
}
cout << "数组的容量为" << arr3.getCapacity() << endl;
}
int main()
{
test01();
system("pause");
return 0;
}