/*
动态数组
*/
class DArray
{
private:
int *base; //数组存储首地址
int length; //数组的长度
int arraySize; //首次分配空间的大小
public:
DArray(int size = 10); //带默认参数,设置为10
DArray(const DArray &r);
~DArray();
void setCount(int s);
bool getValue(int i,int &value); //用value返回值
bool setValue(int i,int v);
};
DArray::DArray(int size)
{
base = new int[size];
this -> length = 0;
this -> arraySize = size;
}
DArray::DArray(const DArray &r)
{
this ->length = r.length;
this ->arraySize = r.arraySize;
this ->base = new int[r.arraySize];
int i = 0;
while(i<r.length)
{
this -> base[i] = r.base[i];
i++;
}
}
DArray::~DArray()
{
if(this -> base)
{
delete []base;
}
arraySize = 0;
length = 0;
}
bool DArray::getValue(int i,int &value)
{
if(i>=this -> length)
{
return false;
}else
{
value = base[i];
return true;
}
}
bool DArray::setValue(int i,int v)
{
if(i>=this -> length)
{
return false;
}else
{
base[i] = v;
return true;
}
}
void DArray::setCount(int s)
{
if(s>this -> length)
{
int *p = new int[s];
int i = 0;
while(i length)
{
p[i] = base[i];
i++;
}
delete []base;
this -> base = p;
}
}
本人C++新手,以上代码有不足之处,烦请各位指正
本文介绍了一个简单的C++动态数组类的实现,包括构造函数、拷贝构造函数、析构函数及基本操作方法如获取和设置元素等。作者作为C++新手,邀请读者指出代码中的不足之处。
741

被折叠的 条评论
为什么被折叠?



