僅當參數中給出的sku字符串與「inventory」數組的成員匹配(數組類型爲* Product且大小爲50)時,incrementStock函數纔會調用「addProduct」函數。我在構造函數中將數組初始化爲nullptr。 「num」是增量編號。 當我測試它並輸入一個有效的SKU到增量庫時,我從addproduct函數中獲得「無空間」。函數調用另一個函數給出錯誤的輸出C++?
void Supplier::addProduct(Product *p)
{
bool space = false;
int counter=0;
while(!space && counter < inventory.size())
{
if(inventory[counter] == nullptr)
{
inventory[counter] = p;
space = true;
}
counter++;
}
if (!space)
{
cout << "no space" << endl;
}
}
void Supplier::incrementStock(const string &sku, int num)
{
bool found = false;
for(int i = 0; i < inventory.size(); i++)
{
if(inventory[i] && sku == inventory[i]->getSKU())
{
found=true;
addProduct(inventory[i]);
inventory[i]->setQuantity(inventory[i]->getQuantity() +num);
}
}
if (found ==false)
{
cout << "not found" << endl;
}
}
爲什麼不直接從零長度庫存數組開始,只需push_back()添加新項目?這樣,您不需要執行所有這些搜索和零比較。 – sj0h
'addProduct'總是填充一個新的空白插槽,即使給出了已經存在於「庫存」中的產品。這是你的意思嗎?如果您爲同一產品調用50次增量庫,您將填滿所有50個插槽。 –
@Igor Tandetnik:謝謝!你的方式讓我意識到我做錯了什麼,我實際上不想像我寫的那樣重新添加同一個成員。 – user3348712