初学乍练, 不好意思!
下面是一道练习题, 大家帮我看看错在哪里?(使用add函数添加元素时,有问题)
///////////////////////////////////////////////////
//list.h: the declaration of the list class
//
///////////////////////////////////////////////////
class list
{
public:
list& add(int pos, int target);
list();
virtual ~list();
private:
int* data;
int maxsize;
int length;
};
//////////////////////////////////////////////////////////////////////
// list.cpp: implementation of the list class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "list.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
list::list()
{
maxsize=1;
data=new int[maxsize];
length=0;
}
list::~list()
{
delete []data;
}
list& list::add(int pos, int target)
{
if(length==maxsize-1)
{
maxsize=maxsize*2;
int* newdata=new int[maxsize];
for(int i=0;i<maxsize-1;i++)
newdata[i]=data[i];
delete []data;
int* data=new int[maxsize];
for(int j=0;j<maxsize-1;j++)
data[j]=newdata[j];
delete []newdata;
}
for(int i=maxsize-1;i>pos;i--)
data[i+1]=data[i];
data[pos]=target;
length++;
return *this;
}