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