C++实现动态数组(不涉及插入删除)

本文介绍了一个简单的C++动态数组类的实现,包括构造函数、拷贝构造函数、析构函数及基本操作方法如获取和设置元素等。作者作为C++新手,邀请读者指出代码中的不足之处。

/*
动态数组
*/

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++新手,以上代码有不足之处,烦请各位指正

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值