我想用数组实现一个类。如果数组的大小被破坏,我会调用 resize() 函数。但是我似乎无法将动态数组编码为数据成员。有人可以指导我如何解决这个问题吗?
这是我到目前为止得到的:
class ArrayList
{
public:
ArrayList()
{
array[ARR_SIZE] = {0};
space = 0;
size = ARR_SIZE;
}
void insert(int place, int value)
{
if (place >= size)
cout << "Sorry, that index is not accessible" << endl;
else
{
array[place] = value;
space++;
if(space == size)
allocate();
}
}
void remove(int place)
{
if(place >= size)
cout << "Sorry, that index is not accessible" << endl;
else
{
array[place] = NULL;
space--;
}
}
void allocate()
{
int* array = new int[size*2];
size = size*2;
}
int usedSize()
{
return space;
}
int totalSize()
{
return size;
}
private:
int array[ARR_SIZE];
int space;
int size;
};
最佳答案
使用std::vector
. C++ 在类或其他方面不支持可变长度或动态大小的数组。
关于c++ - 在类中创建动态数组 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25298266/