[英]I need to dynamically resize an array of objects
每次填滿時,我都需要將數組的大小動態調整為 2。 它以 2 的容量開始。這就是我所做的(在 main.cpp 中),但它給了我這些錯誤:“警告:刪除數組'test'”和“錯誤:'ItemInfo * 分配中的不兼容類型” ' 到 'ItemInfo [cap]'”。
ItemInfo test[cap];
//I have code here to open file, read from file, etc
if(itemCount >= cap){
cap += 2;
ItemInfo *temp;
temp = new ItemInfo[cap];
for(int i = 0; i < cap; i++){
temp[i] = test[i];
}
delete[] test; //error here
test = temp; //error here
}
這是 class(in.hpp 文件):
#include <iostream>
#include <iomanip>
using namespace std;
class ItemInfo {
private:
int itemId;
char description[40];
double manCost;
double sellPrice;
public:
ItemInfo() {
itemId = 0;
*description = '\0';
manCost = 0.0;
sellPrice = 0.0;
}
void setItemId(const char *num);
void setDescription(const char *cstr);
void setManCost(const char *num);
void setSellPrice(const char *num);
int getItemId();
const char *getDescription();
double getManCost();
double getSellPrice();
問題是你使用ItemInfo test[cap];
. 使用此聲明導致test
被保存在堆棧中。 因此,它具有恆定的大小。 使用temp = new ItemInfo[cap];
在堆上動態分配 memory。 這是您也可以免費撥打的 memory。 因此, test
和temp
是不同的類型,無法釋放test
。 ItemInfo *test = new ItemInfo[cap];
應該為你工作。
還要注意還有一個小錯誤:在應該使用舊cap
的地方增加cap
后,您復制了第一個cap
的許多值。
如果ItemInfo
可以輕松復制,則您也可以使用realloc
,這樣您就不需要循環來復制數據並暫時使用比可能需要的更多的 memory。 使用 realloc 的代碼看起來像
ItemInfo *test = (*ItemInfo) malloc(cap * sizeof(ItemInfo));
// use malloc here as realloc and new should not be mixed
[...]
if(itemCount >= cap){
cap += 2;
test = (*ItemInfo) realloc(test, cap * sizeof(ItemInfo));
}
正如 user4581301 提到的,如果沒有什么特別反對的話,您也可以嘗試使用Vectors
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.