我有一个存储“ InventoryItem”的库存。
struct InventoryItem{
Item* item;
unsigned int quantity;};
std::vector<InventoryItem> m_items;
我添加以下内容 m_inventory.addItem(bandage);
但是,当我尝试调用use()
从Item基类派生的绷带功能时,它会use()
改为调用Item类功能。
像这样在Item类中声明了它,
// ....
public:
// ....
virtual void use(Player&){}
// ....
像这样在绷带类中声明了它,
// ....
class Bandage : public Item{
public:
// ....
virtual void use(Player&);
// ....
像这样在Bandage类中定义了它,
void Bandage::use(Player& player)
{
player.heal(35);
}
例如,当我尝试调用项目的use()
功能时,m_items.at(i).item->use(*m_player);
它调用基类的“项目”use()
功能,而不是“绷带”use()
功能。
编辑:这是我的addItem函数,
void Inventory::addItem(const Item& item)
{
if ((m_items.size() < m_capacity))
{
bool foundItem(false);
for (auto invItem : m_items)
{
// if the item already exists, lets just increase the quantity
if (invItem.item->getID() == item.getID())
{
foundItem = true;
if (invItem.quantity < invItem.item->getInventoryQuantityLimit())
{
++invItem.quantity;
}
}
}
if (!foundItem){
m_items.push_back(InventoryItem{ new Item(item), 1 });
}
}
}
问题出在您的addItem()
职能上,更确切地说是在这里:
m_items.push_back(InventoryItem{ new Item(item), 1 });
指针Item*
在InventoryItem
端部向上指向一个Item
,而不是从派生的对象Item
,即使item
是一个派生对象。该表达式new Item(item)
不会创建派生对象,而是Item
使用派生对象item
作为参数来调用(如果未编写,则为默认值)副本构造函数。然后,它Item
在堆上创建对象,并返回指向它的指针。
使用创建所需项的工厂方法会更好,并且摆脱掉原始指针的支持std::shared_ptr
(或std::unique_ptr
,尽管这里可能std::shared_ptr
更好)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句