用类实现动态数组

#include<iostream>
using namespace std;
class Array
{
   
private:
	int size;
	int* a;
public:
	Array(int sz=0);
	Array(const Array& a);
	~Array();
	void push_back(int n);//数组尾部添加元素
	int length();
	int& operator[](int n);
	Array& operator=(const Array& a);
};
//涉及空指针,注意考虑
Array::Array(int sz):size(sz)
{
   
	if (sz == 0)a = NULL;//考虑sz为空的情况
	else a = new int[size];
}
Array::Array(const Array& b)
{
   
	if (!b.a)//拷贝对象为空
	{
   
		a = NULL;
		size = b.size;
		return;
	}
	else
	{
   
		size = b.size;
		a = new int[size];
		int* to = a, * from = b.a, i = size;
		while (i--)
			*(to++) = *(from++);
	}
}
Array::~Array()
{
   
	if(a)delete[]a;//不是空指针
}
void Array::push_back(int n)
{
   
	if (a)
	{
   
		int* ptr = new int[size + 1];
		int i = size, * to = ptr, * from = a;
		while (i--)
		{
   
			*(to++) = *(from++);
		}
		a = ptr;
	}
	else a = new int[1];
	a[size++] = n;
}
int Array::length()
{
   
	return size;
}
int& Array::operator[](int n)
{
   
	return a[n];
}
Array& Array::operator=(const Array& b)
{
   
	if (!b.a)//拷贝对象为空
	{
   
		if (a)delete[]a;//涉及空指针,先判断再delete
		a = NULL;
		size = b.size;
		return*(this);
	}
	else if (b.a == a);//内容相同
	else if (b.size != size)//长度不相等
	{
   
		if (a)delete[]a;
		size = b.size;
		a = new int[size];
	}
	//赋值,深拷贝
	{
   
		int* to = a, * from = b.a, i = size;
		while (i--)
			*(to++) = *(from++);
	
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值