【问题标题】:function calling another functions gives wrong output c++?调用另一个函数的函数给出错误的输出c++?
【发布时间】:2014-02-28 02:15:06
【问题描述】:

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

【问题讨论】:

  • 为什么不从零长度的库存数组开始,然后只用 push_back() 添加新项目?这样您就不需要进行所有这些搜索和零比较..
  • addProduct 总是填充一个新的空槽,即使给定的产品已经存在于inventory 中。这是你的意思吗?如果您为同一产品拨打incrementStock 50 次,您将填满所有 50 个位置。
  • @Igor Tandetnik:谢谢!你说的方式让我意识到我做错了什么,我实际上不想像我写的那样重新添加同一个成员。

标签: c++ arrays function output


【解决方案1】:

考虑这个循环:

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

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

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

【讨论】:

  • 没错,这就是为什么我不断收到长页的消息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多