【问题标题】:C++ OOP inventory and item classC++ OOP 库存和项目类别
【发布时间】:2018-02-12 23:24:54
【问题描述】:

创建 Inventory 类以及 item 类...处理库存“移除”库存中的项目。

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

//这是在actor类中...

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

问题是......我不确定在 Inventory 类的 Item Inventory 函数中做什么,它应该返回一些东西,但我不知道为什么......老师无法访问。如果它应该返回一个 Item 对象,我需要从整数值中获取 Item 对象。 Item 对象类有一个 char* 名称;和 int numItem;

【问题讨论】:

  • 我在这里没有看到任何实际问题。
  • 澄清了这个问题。
  • 我的猜测是 Item 是索引函数(类似于 [] 运算符),它返回指定为 0 或 1 的插槽中的项目,具体取决于您的规范。
  • 您的rubber duck 想知道您希望如何在列表中删除后找到并返回该项目。
  • 如果有更好的写法,请大哥帮忙。我同意返回一个将要删除的值是愚蠢的。这就是为什么我对退货部分也感到困惑......

标签: c++ class inventory


【解决方案1】:

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

好的,你离这里很近了。从您的描述看来,Item 被定义为

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

而您的itemsItem 的STL 容器,我们将使用std::vector&lt;Item&gt; 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;
}

如果没有找到num 的任何匹配项,则返回默认构造的Item 有点尴尬,但是如果您想检测这种情况,您总是可以执行一些操作,例如将其初始化为“假”值,您知道不能在您的库存中。

【讨论】:

  • 赞成,但我会将 ++it 移到 for 循环中,因为 A)在那里并不令人惊讶 B)当擦除发生时循环退出,所以你不必担心 @ 987654337@ 在死迭代器上。
猜你喜欢
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 2017-07-04
  • 2013-12-17
相关资源
最近更新 更多