C++ OOP 库存和项目类

C++ OOP inventory and item class

本文关键字:项目 OOP C++      更新时间:2023-10-16

创建库存类以及项目类...处理库存 从库存中"删除"项目。

#include "Inventory.h"
#include <iostream>
void Inventory::PrintInventory() {
for (auto i = items.begin(); i != items.end(); i++) {
std::cout << i->name << " " << i->numItem << std::endl;
}
}
void Inventory::ReceiveItem(Item item) {
items.push_back(item);
}
Item Inventory::TakeItem(int num) {
items.erase(items.begin() + num);
auto item = std::find(items.begin(), items.end(), num);
//issue is here
//my teacher said to set it up as Item Inventory that takes in an int.
return item;
}

//这是在演员类...

void Actor::GiveItem(Actor* actor, Item item) {
int num = item.numItem;
actor->inventory.ReceiveItem(item);
inventory.TakeItem(num);
}

问题是...我不确定在 Inventory 类的物品清单函数中该怎么做,它应该返回一些东西,但我不确定为什么。老师联系不上。如果它应该返回一个 Item 对象,我需要从整数值中获取 Item 对象。Item 对象类具有 char* 名称;和整数项;

它应该返回一个Item对象,我需要从整数值中获取Item对象。

好的,所以你离这里很近。 从您的描述中听起来Item被定义为

struct Item
{
std::string name;
int numItem;  ///< search for this value
};

而你的itemsItem的STL容器,我们将使用std::vector<Item> items;

如果必须返回Item对象,则应声明默认Item以在出错时返回。如果成功找到Item::numItem的匹配项,则将使用这些值填充默认Item。最后,如果您确实找到了要拿走的物品,您将将其擦除以进行库存内务管理。出于显而易见的原因,在找到Item之前不要擦除它!

Item TakeItem(int num)
{
Item localItem;
for (auto it = items.begin(); it != items.end();) {
// if we find a match set local item and then
// remove the item from inventory
// and break out of loop since we are done
if ((*it).numItem == num) {
localItem = *it;
it = items.erase(it);
break; // found and removed from inventory!
} else {
++it;
}
}
return localItem;
}

在找不到任何匹配项的情况下返回默认构造Item有点尴尬num但是如果您想检测这种情况,您可以随时将其初始化为已知不能在您的清单中的"虚假"值。