根据郝斌的视频--数组的类的实现

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
class Arr 
{

	int cnt;   //当前数组元素的个数
	int len;   //该数组的个数
	int * pBase;  //数组首地址的指针
public:
	Arr() = default;  //默认构造函数
	Arr(int n) :len(n) { this->pBase = (int *)malloc(sizeof(int)*len); };  //一个参数的构造函数
	bool append_arr(const int val )      //隐式内联函数
	{
		if (this->cnt >= this->len)
		{
			printf("该数组已满");
			return false;
		}
		else 
		{
			this->pBase[cnt] = val;
			this->cnt = this->cnt + 1;
			return true;
		}
	}
	bool insert_arr(const int index, const int val)
	{
		if (index > len || index <= 0)
		{
			printf("插入的index有误");
			return false;
		}
		else
		{
			for (int i = this->cnt; i > index - 1; i--)
				this->pBase[i] = this->pBase[i - 1];
			this->pBase[index - 1] = val;
			this->cnt = this->cnt + 1;
			return true;
		}

	}
	bool is_empty() 
	{
		if (this->cnt == 0)
			return true;
		else
			return false;
	}
	bool delete_arr(const int index)   //隐式内联函数不用this指针,也可以使用私有变量
	{
		if (index > cnt || index <= 0)
		{
			printf("index有误\n");
			return false;
		}	
		if (is_empty())
		{
			printf("数组为空!!\n");
			return false;
		}
		else 
		{
			for (int i = index - 1; i <= cnt - 1; i++)
				pBase[i] = pBase[i + 1];
			cnt = cnt - 1;
			return true;
			
		}
	}
	inline bool is_full();   //显式内联函数
	inline int get(const int index);
	void showArr()
	{
		if (this->is_empty())
		{
			printf("数组为空!!\n");
		}
		else 
		{
			for (int i = 0; i < this->cnt; i++)
			{
				printf("%d ", this->pBase[i]);
			}
			printf("\n");
		}
	}


};
bool Arr::is_full()  //显式内联函数也可以不用this指针,来调用私有变量
{
	if (cnt == len)
	{
		return true;
	}
	else
		return false;
}
int Arr::get(const int index)
{
	if (index > cnt || index <= 0)
	{
		printf("对不起您查询的index不存在\n");
		exit(-1);
	}
	else
	{
		return pBase[index - 1];
	}
		
}
int main()
{
	Arr arr(6);
	arr.append_arr(1);
	arr.append_arr(2);
	arr.append_arr(3);
	arr.append_arr(4);
	arr.delete_arr(2);
	arr.showArr();
	int n = arr.get(5);
	bool flag = arr.is_full();
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值