2014-02-25 69 views
0

我在removeItem方法中遇到問題,因爲在調用它之後發生錯誤。 在這種方法中,我試圖在nullptr的參數中設置sku的數組成員並將其「刪除」。 我認爲這與均衡有關:if(sku == shoppingList[i]->getSKU())。或者可能與const有關。該數組有指向Product類型的對象的指針。在方法C++中設置const的字符串是否相等?

這屬於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; 
} 
+1

什麼是shoppingList的類型?爲什麼不使用擦除/刪除成語? – Borgleader

+0

private: std :: array shoppingList; – user3348712

回答

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

我覺得現在的問題是,你試圖調用一個方法的指針產品,已經被設置爲nullptr

+0

非常感謝你!那工作。 – user3348712

+0

@ user3348712祝你好運。 –

0

我最好的猜測是,你的代碼不寫入來處理數組中的nullptr條目。由於您沒有真正顯示錯誤發生的位置或購物清單的類型,因此很難確切地說出錯。將std::string*設置爲nullptr不會將其從std::string*類型的數組中移除。如果您有興趣輕鬆移除項目,請考慮使用不同的數據結構。

相關問題