2013-02-02 25 views
0

當我嘗試在列表中使用push_back方法時出現編譯器錯誤。嘗試push_back在列表上。 C++

這裏是我的代碼:

// Point iterator to the proper warehouse. 
set<cs3505::warehouse>::iterator curr_warehouse = warehouses.find(warehouse); 

// Insert new inventory_item into the warehouse. 

// Create a copy of today's date, and increment it. 
cs3505::date exp_date = current_date; 
exp_date.increment(curr_food.get_shelf_life()); 

// Create a new inventory item. 
cs3505::inventory_item new_item(curr_food, exp_date); 
// Set the quantity of the new item. 
new_item.set_quantity(qty); 

// Now insert the item. 
// Adding new items being at the end ensures the oldest items will be at the 
// beginning of the list. 
(*curr_warehouse).inventory.push_back(new_item); 

編譯器錯誤:

report.cc:134: error: passing ‘const std::list >’ as ‘this’ argument of ‘void std::list<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = cs3505::inventory_item, _Alloc = std::allocator]’ discards qualifiers

我的代碼的最後一行是管線134感謝您的幫助。幾個小時以來,我一直在嘲笑我的頭。

這是一個inventory_item的定義:

/* 
* An inventory item which includes a food item, an expiration date, 
* and quantity. 
*/ 

#include "inventory_item.h" 
#include "date.h" 
#include "food_item.h" 

namespace cs3505 
{ 
// inventory_item definitions 

/* 
* Constructs an inventory item. 
*/ 
inventory_item::inventory_item(food_item &item, date &exp_date) 
{ 
    this->item = item; 
    this->expiration_date = exp_date; 
    this->quantity = 0; 
} 

/* 
* Destructs a food item. 
*/ 
inventory_item::~inventory_item() { } 

/* 
* Returns this inventory item's food item. 
*/ 
food_item inventory_item::get_food_item() 
{ 
    return this->item; 
} 

/* 
* Returns the expiration date for this inventory item. 
*/ 
date inventory_item::get_exp_date() 
{ 
    return this->expiration_date; 
} 

/* 
* Returns the quantity of this inventory item. 
*/ 
int inventory_item::get_quantity() 
{ 
    return this->quantity; 
} 

/* 
* Sets the quantity of this food item. 
*/ 
void inventory_item::set_quantity(int change) 
{ 
    this->quantity = change; 
} 
} 

我也有,有一個列表的自定義倉庫類。我正在嘗試將清單項目添加到該列表中。

+0

什麼是'new_item'? –

+0

此代碼是否駐留在const成員函數中? – Fraser

+0

new_item是我想添加到清單中的新庫存項目 – LuckyPrime

回答

2

這裏的錯誤是因爲您忽略const限定符。這是因爲由集合返回的迭代器必須爲爲const。這個限制是適當的,因爲一個集合中的所有元素必須是唯一的;通過迭代器更改集合中元素的值可能會破壞此合約。

我無法找到確切的參考副手(和SGI對std::set參考並沒有提到這一點),所以不是我將通過鏈接到另一個#2發佈說明這一點:C++ STL set update is tedious: I can't change an element in place

編輯:找到它。

std::setSimple Associative Container的一種,意思是這些值與密鑰相同。接下來的段落總結了這一點:

The types X::iterator and X::const_iterator must be the same type. That is, a Simple Associative Container does not provide mutable iterators.

這確實意味着我的第一段在技術上有點不對。這並不是要確保你不會將一個集合的元素從下面改變爲相同的值,而是僅僅通過設計。它實際上是「基礎不變」的副作用,基礎概念不變。

儘管如此,我還是不想讓它成爲一個重要的編輯。

+0

感謝您的幫助。 – LuckyPrime