C++ 更新数组(?)时出现问题
我正在尝试为一个基于文本的冒险游戏创建一个库存系统,我们需要分配一个任务,但是我的物品数组有问题 当我尝试更改/更新数组中的某个项时,它会“更新”,但当我在该项未更新后使用命令循环该项时 编辑方法可以正确打印 我需要一些帮助C++ 更新数组(?)时出现问题,c++,C++,我正在尝试为一个基于文本的冒险游戏创建一个库存系统,我们需要分配一个任务,但是我的物品数组有问题 当我尝试更改/更新数组中的某个项时,它会“更新”,但当我在该项未更新后使用命令循环该项时 编辑方法可以正确打印 我需要一些帮助 void Inventory::edit(int slot, Item item) { cout << "changing slot: " << slot << endl; cout << "old Id: "
void Inventory::edit(int slot, Item item)
{
cout << "changing slot: " << slot << endl;
cout << "old Id: " << this->items[slot].getId() << endl;
this->items[slot] = item;
cout << "new Id: " << this->items[slot].getId() << endl;
}
changing slot: 0
old Id: -1
new Id: 1
void Inventory::printInventory()
{
cout << "Your inventory:" << endl;
for (Item item : this->items) {
cout << "id: " << item.getId() << endl;
}
}
prints
Your inventory:
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
id: -1
项目.h
#包括
使用名称空间std;
类项目
{
私人:
int-id;
整数金额;
布尔可堆叠;
公众:
//用于设置项目的金额
无效设置金额(整数金额);
//用于抓取项目的金额
int getAmount();
//设置项目id
void setId(int id);
//获取项目id
int getId();
项目();
~Item();
//用于生成仅具有id的项目,将自动将金额设置为1
项目(内部id);
//用于生成具有id和设置数量的iteem
项目(整数id、整数金额);
//获取项的名称
字符串getName();
//获取项是否可堆叠
布尔可跟踪();
};
在Player类中,必须通过引用返回
进行修改:
Player.cpp
Player.h
如何定义
库存
?什么是项目
?什么是项
?如何调用edit
?请提供。在使用副本(按值传递)的函数中,尝试添加引用:void Inventory::edit(int slot,Item&Item)@SergeyA,但我看不到项
的修改位置。@AlgirdasPreidžius其在我的玩家类中的定义如下:Inventory Inventory;和items是我的Item类Item items的数组[28];在我的库存中。h@NighelNijhuis我要了。您的示例仍然不完整(我们无法复制、粘贴、运行和重现相同的问题)。注意:我不是要求完整的代码。我要的是人造的。非常感谢。这确实是个问题。我会读更多关于参考资料的书。
#pragma once
#include "Item.h"
using namespace std;
class Inventory
{
private:
public:
Inventory();
~Inventory();
Item items[28];
void clear();
void edit(int slot, Item item);
void add(Item item);
void add(Item item, int slot);
void remove(Item item);
bool contains(string name);
int getNextFreeSlot();
int getSlot(int itemId);
int freeSlots();
void printInventory();
};
#include <string>
using namespace std;
class Item
{
private:
int id;
int amount;
bool stackable;
public:
//Used for setting the amount of the item
void setAmount(int amount);
//Used for grabbing the amount of the item
int getAmount();
//Sets the item id
void setId(int id);
//Grabs the item id
int getId();
Item();
~Item();
//Used for generating an item with just an id, will automaticlly set the amount to 1
Item(int id);
//Used for generating an iteem with an id and an set amount
Item(int id, int amount);
//Gets the name of an item
string getName();
//Gets if an item is stackable
bool isStackable();
};
Inventory& Player::getInventory()
{
return this->inventory;
}
Inventory& getInventory();