C++ OOP 库存和项目类
C++ OOP inventory and item class
创建库存类以及项目类...处理库存 从库存中"删除"项目。
#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
};
而你的items
是Item
的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
但是如果您想检测这种情况,您可以随时将其初始化为已知不能在您的清单中的"虚假"值。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 欧拉项目#8答案是大以获得有效答案
- 从链接列表c++中删除一个项目
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 既然存在危险,为什么项目要使用-I include开关
- cmake在我的项目中所需的所有静态库都不成功
- QT通过C++添加映射QML项目
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在linux上调试巨大的C++项目
- 在其他文件中创建类时在 c++ 项目中不起作用
- 使外部项目可用于find_package CMake
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- C++ OOP 库存和项目类
- 我得到了一个使用 SDL 的 OOP 项目。我没有使用继承。我可以给我的评估员什么理由
- 如何正确构建 OOP 和多文件项目
- OOP项目功能错误