在方法c ++中设置const字符串是否相等?

时间:2014-02-25 23:31:55

标签: c++ error-handling equals-operator

我遇到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;
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

按以下方式更改方法

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;
        }
    }
}

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