C++:数组的封装
#include <iostream>
#include <string>
using namespace std;
class Array
{
private:
int capacity; // 数组容量
int size; // 数组大小
int* pArr; // 数组指针
public:
// explicit关键字用于避免隐式法对象创建
explicit Array(const int& capacity) // 有参构造函数
{
this->capacity = capacity;
this->size = 0;
this->pArr = new int[this->capacity]; // 堆上开辟内存空间
}
Array(const Array& arr) // 拷贝构造函数
{
this->capacity = arr.capacity;
this->size = arr.size;
this->pArr = new int[this->capacity];
memcpy(this->pArr, arr.pArr, this->size*sizeof(int));
}
// 赋值运算符重载
Array& operator=(const Array& arr)
{
if(NULL!=this->pArr)
{
delete[] this->pArr;
this->pArr = NULL;
}
this->capacity = arr.capacity;
this->size = arr.size;
this->pArr = new int[this->capacity];
memcpy(this->pArr, arr.pArr, this->size*sizeof(int));
return *this;
}
~Array()
{
this->capacity = 0;
this->size = 0;
if(NULL!=this->pArr)
{
delete[] this->pArr;
this->pArr = NULL;
}
}
int Length() const
{
return this->size;
}
int Get(const int& pos) const
{
return this->pArr[pos];
}
void Append(const int& data)
{
this->pArr[this->size] = (int)data;
++this->size;
}
void Set(const int& pos, const int& data)
{
this->pArr[pos] = (int)data;
}
//[]运算符重载
int& operator[](int index) const
{
return this->pArr[index];
}
};
void test01()
{
Array arr(10);
for(int i=0; i<10; i++)
{
arr.Append(i);
}
arr.Set(0, 20);
for(int i=0; i<10; i++)
{
cout<<arr.Get(i)<<" ";
}
cout<<endl;
cout<<"new: "<<arr[0]<<endl;
arr[0] = 100;
for(int i=0; i<10; i++)
{
cout<<arr.Get(i)<<" ";
}
}
int main()
{
test01();
return 0;
}