函数调用另一个函数会给出错误的输出 C++

function calling another functions gives wrong output c++?

本文关键字:错误 输出 C++ 出错 另一个 函数 函数调用      更新时间:2023-10-16

仅当参数中给出的 sku 字符串与 "inventory" 数组的成员匹配时,增量库存函数才会调用 "addProduct" 函数(数组类型为 *Product 且大小为 50)。我在构造函数中将数组初始化为 nullptr。"num"是增量数字。当我测试它并输入有效的 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;
        }
}

考虑这个循环:

    for( int i = 0; i < inventory.size(); i++ )

如果您在此循环中获得 SKU 匹配项,则会将该商品的额外副本添加到库存中。 这有点奇怪,但如果你想要在库存中拥有同一指针的多个副本,那很好。

问题是,在循环的那次迭代之后,循环会继续,它也会找到我们刚刚做的副本,看到它匹配,然后再次制作另一个副本。 重复此操作,直到数组已满。