我有一个名为 values 的整数数据数组,我需要在数组中插入一个新的 Integerdata。我曾考虑制作一个临时数组来复制所有内容,然后制作一个大小为原始数组 + 1 的新数组,但我不断收到很多错误。有什么帮助吗?
class IntegerData : public Data {
public:
int value;
// This is the syntax for a constructor that initializes the
// properties value to the parameters
IntegerData(int value) : value(value) {}
}
class ArrayCollection : Collection {
// length of values is always the same as count
Data ** values;
int count;
public:
ArrayCollection() {
// initialize the array to NULL
this->values = NULL;
this->count = 0;
}
~ArrayCollection() {
// must clean up the internally allocated array here
if (values != NULL) {
delete [] values;
}
}
/**
* Returns the count of the number of elements in the Collection
*/
int size() const {
return count;
}
/**
* Gets the Data value at the specified index. If index >= size() then
* NULL is returned.
*/
Data * get(int index) {
if (index >= size()) {
return NULL;
}
else {
return values[index];
}
}
????-- I need help with this method--
// I try to dynamically allocate tempArray but I get the error message saying: cannot
// allocate an object of abstract type 'Data'
void insert(Data * other){
count++;
Data **tempArray = new Data[count];
for(int i = 0; i < count; i++){
tempArray[i] = values[i];
}
delete [] values;
values = tempArray;
}
}
int main(int argc, const char * argv[]) {
// create an ArrayCollection for our collection of integers
ArrayCollection * collection = new ArrayCollection();
if (argc == 1) {
// they didn't provide any arguments to the program, insert a
// value of zero so that the main function still works
collection->insert(new IntegerData(0));
}
else {
for (int i = 1; i < argc; i++) {
// read user input for integer value
int x = atoi(argv[i]);
// insert it to our collection
collection->insert(new IntegerData(x));
}
}
// print the collection
cout << collection->toString() << endl;
// check the implementation of member
IntegerData * five = new IntegerData(5);
cout << "five is a member of collection? " << collection->member(five) << endl;
// now we are going to insert and remove a few items -- MARKER (a)
IntegerData * v0 = (IntegerData *)collection->get(0);
collection->remove(v0);
cout << collection->toString() << endl;
// check after removing the 0th element -- MARKER (b)
cout << "five is a member of collection? " << collection->member(five) << endl;
collection->insert(v0);
cout << collection->toString() << endl;
// check after inserting the 0th element back
cout << "five is a member of collection? " << collection->member(five) << endl;
// clean up memory
delete five;
// must delete IntegerData instances that we allocated in main
// because they are not deleted by the data structure
for (int i = 0; i < collection->size(); i++) {
delete collection->get(i);
}
// now delete the data structure -- MARKER (c)
delete collection;
}