C++:数组的封装

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值