C++建立动态数组

来源:百度知道 编辑:UC知道 时间:2024/06/27 16:18:48
2. 设计一个SafeArray类,该类用于维护一个动态的int数组,提供安全的访问、删除及插入功能。需要满足以下条件:
(1) 构造函数SafeArray(size_t size): 创建一个大小为size的int数组,初始值为0。
(2) 提供getValue和setValue函数,用于获取和改变数组中指定元素的值。
(3) 提供删除和插入函数,用于在指定位置插入和删除元素。
最后在main函数中测试SafeArray的各个功能。
怎么建立动态数组啊 还有怎么实现哪些功能啊 哪位大哥教一个我这个菜鸟啊 能把程序帮我写一下吗?谢谢啊

#ifndef H_array
#define H_array
class safeArray
{
public:
int getvalue(int location);
void setvalue(int location,int value);
void add(int location,int value);
void addend(int value);
void remove(int location);
void print();
safeArray(int size=10);
private:
int csize; //数组的存储空间长度
int cmax; //已存的数组长度
int *list;
};
#endif

前面保存为array.h

#include <iostream>
#include "array.h"
using namespace std;

int safeArray::getvalue(int location)
{
if(location<0 || location>=cmax)
cout<<"the location is wrong"<<endl;
else
return (list[location]);
}

void safeArray::setvalue(int location,int value)
{
if(location<0 || location>=cmax)
cout<<"the location is wrong"<<endl;
else
list[location]=value;
}