我遇到了问题 removeItem 方法,因为调用该方法后会立即发生错误。在此方法中,我尝试使用以下方法设置数组成员 sku 在论证中 nullptr 并“删除”它。我认为这与均衡有关: if(sku == shoppingList[i]->getSKU()). 。或者也许与以下有关 const. 。该数组具有指向类型对象的指针 Product.

这属于 CustomerOrder.cpp

CustomerOrder::CustomerOrder()
: shoppingList()
{

}
void CustomerOrder::removeItem(const string &sku)
{
    for(int i =0; i< 20; i++)
    {
        if(sku == shoppingList[i]->getSKU())
        {
            shoppingList[i] = nullptr;
        }
    }
}

这属于 Product.h

private:
std::string sku;

这属于 Product.cpp

const string & Product::getSKU() const
{
    return sku;
}
有帮助吗?

解决方案

将方法更改为以下方式

void CustomerOrder::removeItem( const string &sku )
{
    for( int i = 0; i < shoppingList.size(); i++ )
    {
        if( shoppingList[i] && sku == shoppingList[i]->getSKU() )
        {
            delete shoppingList[i];
            shoppingList[i] = nullptr;
        }
    }
}

我认为问题在于您尝试调用已设置为 nullptr 的 Product 指针的方法

其他提示

我最好的猜测是您的代码不是为处理数组中的 nullptr 条目而编写的。由于您实际上没有显示错误发生的位置或购物清单的类型,因此很难准确地说出出了什么问题。设置一个 std::string* to nullptr 不会将其从类型数组中删除 std::string*. 。如果您对轻松删除项目感兴趣,请考虑使用不同的数据结构。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top