[英]function calling another functions gives wrong output c++?
The incrementStock function calls the "addProduct" function only if the sku string given in the argument matches with a member of the "inventory" array (the array is of type *Product and of size 50). 仅当参数中给定的sku字符串与“库存”数组的成员(数组的类型为* Product且大小为50)匹配时,增量股票函数才调用“ addProduct”函数。 I initialized the array to nullptr in the constructor. 我在构造函数中将数组初始化为nullptr。 "num" is the increment number. “ num”是增量数。 When I test it and enter a valid sku to incrementStock, I get "no space" from the addproduct function. 当我对其进行测试并输入有效的sku来递增股票时,我从addproduct函数中获得“无空间”。
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;
}
}
Consider this loop: 考虑以下循环:
for( int i = 0; i < inventory.size(); i++ )
If you get a match for sku within this loop, it will add an extra copy of that item into inventory. 如果在此循环中找到sku的匹配项,它将在库存中添加该项目的额外副本。 That's a bit odd, but fine if you want multiple copies of the same pointer in inventory. 有点奇怪,但是如果您要在清单中复制同一指针的多个副本,那就很好了。
The problem is that after that iteration of the loop, the loop will continue, and it will also find the copy we just made, and see that it matches, and then make another copy again. 问题在于循环的迭代之后,循环将继续,并且还将找到我们刚刚制作的副本,并查看它是否匹配,然后再次制作另一个副本。 This repeats until the array is full. 重复此操作,直到阵列已满。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.