强化封装——数组类封装
MyArray.h
class MyArray {
public:
MyArray();//默认构造,默认100容量
MyArray(int capacity);
MyArray(const MyArray& array);//拷贝
~MyArray();//拷贝
void push_Back(int val);//尾插法
int getData(int index);//根据索引获取值
void setData(int index, int val);//根据索引设置值
int getSize();//获取数组大小
int getCapacity();//获取数组容量
private:
int* pAddress;//指向真正存储数据的指针
int m_Size;//数组的大小
int m_Capacity;//数组的容量
};
MyArray.cpp
#include "MyArray.h"
/*
private:
int* pAddress;//指向真正存储数据的指针
int m_Size;//数组的大小
int m_Capacity;//数组的容量
*/
//默认构造
MyArray::MyArray()
{
this->pAddress = new int[this->m_Capacity];
this->m_Size = 0;
this->m_Capacity = 100;
}
//有参构造 参数是数组容量
MyArray::MyArray(int capacity)
{
cout << "Parametric constructor." << endl;
this->pAddress = new int[this->m_Capacity];
this->m_Size = 0;
this->m_Capacity = capacity;
}
//拷贝构造
MyArray::MyArray(const MyArray& array)
{
cout << "Copy Constructor." << endl;
this->pAddress = new int[array.m_Capacity];
this->m_Size = array.m_Size;
this->m_Capacity = array.m_Capacity;
for (int i = 0; i < array.m_Size; i++) {
this->pAddress[i] = array.pAddress[i];
}
}
//析构
MyArray::~MyArray()
{
if (this->pAddress != NULL) {
cout << "Destructor and pAddress is not NULL." << endl;
delete[] this->pAddress;
this->pAddress = NULL;
}
}
void MyArray::push_Back(int val)
{
//越界?用户处理
this->pAddress[this->m_Size] = val;
this->m_Size++;
}
int MyArray::getData(int index)
{
return this->pAddress[index];
}
void MyArray::setData(int index, int val)
{
this->pAddress[index] = val;
}
int MyArray::getSize()
{
return this->m_Size;
}
int MyArray::getCapacity()
{
return this->m_Capacity;
}
main.cpp
void testMyArray() {
//堆区创建数组
MyArray* array = new MyArray(30);
//new 方式指定调用拷贝构造
MyArray* array2 = new MyArray(*array);
//构造函数返回的本体
MyArray array3 = *array2;
//这个是声明一个指针和 array 执行地址相同
//不会调用拷贝构造
//MyArray* array2 = array;
for (int i = 0; i < 10; i++) {//尾插
array2->push_Back(i);
}
for (int i = 0; i < 10; i++) {//数据获取
cout << array2->getData(i) << endl;
}
array2->setData(0, 1000);//设置值
cout << array2->getData(0) << endl;
cout <<"Size: " << array2->getSize() << endl;
cout <<"Capacity: " << array2->getCapacity() << endl;
/*
获取 设置数组内容
如何用[]设置?
cout<<array3[0]<<endl;
array3[0]=10;
*/
delete array;
}