C++文本RPG项目vector实现背包及装备系统出现语法错误求助
C++ RPG背包系统代码错误修复
已发现的错误点
- 装备模块下标非法:
Equipment[Inventory[i].purpose]代码中使用字符串类型的装备类型作为vector下标,C++中数组/vector下标仅支持整数类型,无法直接传入字符串取值。 - 背包输出逻辑错误:直接使用
cout << Inventory[i]输出自定义Item结构体,C++没有默认的结构体输出规则,需要单独输出成员或者重载<<运算符。 - 拼写小问题:
InventorySlots数组中的Objec1拼写错误,应为Object1。
修正后的完整代码
// inventorySysteme.cpp : This file contains the 'main' function. Program execution begins and ends there. #include <iostream> #include <vector> #include <string> #include <Windows.h> using namespace std; struct Item{ string name; // 物品名称 string purpose; // 装备类型:weapon, armor等 int stats; // 攻击/护甲数值 int attribute; // 0 = 无 1 = 护甲穿透 2 = 法术伤害等 }; // 重载<<运算符支持直接输出Item对象 ostream& operator<<(ostream& os, const Item& item) { os << "物品名:" << item.name << " | 类型:" << item.purpose << " | 属性值:" << item.stats; if (item.attribute == 1) os << " | 特效:护甲穿透"; else if (item.attribute == 2) os << " | 特效:法术伤害"; return os; } // 工具函数:根据装备类型找第一个空闲的装备栏位 int getEmptyEquipSlot(const vector<string>& Equipment, const string& purpose) { if (purpose == "Weapon") { // 前两个是武器位 for (int i = 0; i < 2; i++) { if (Equipment[i] == "Empty") return i; } } // 后面是道具位,可根据需求扩展护甲、饰品等位置的判断 for (int i = 2; i < 5; i++) { if (Equipment[i] == "Empty") return i; } return -1; // 没有空闲位置 } int main() { Item Sword{ "RustedSword", // 名称 "Weapon", // 武器类型 10, // 10点攻击 1 // 护甲穿透 }; Item Staff{ "FirerStaff", "Weapon", 20, 2 }; string input; // 玩家输入内容 vector<string> Equipment = { "Empty", "Empty", "Empty", "Empty", "Empty" }; // 装备栏空位标识 string InventorySlots[] = { "Weapon", "Weapon", "Object1", "Object2", "Object3" }; // 背包栏位类型 vector<Item> Inventory = { Sword, Staff }; // 背包存储 while (true) { cin >> input; if (input == "equipment") { for (int i = 0; i < 5; i++) { cout << InventorySlots[i] << " " << Equipment[i] << "\n\n"; } } // 装备逻辑 if (input == "equip") { cout << "请输入你要装备的物品名:\n"; cin >> input; for (int i = 0; i < Inventory.size(); i++) { if (input == Inventory[i].name) { int slot = getEmptyEquipSlot(Equipment, Inventory[i].purpose); if (slot != -1) { Equipment[slot] = Inventory[i].name; cout << "装备成功!" << endl; } else { cout << "对应装备栏已满,无法装备!" << endl; } break; } } } // 背包展示逻辑 if (input == "inventory") { for (int i = 0; i < Inventory.size(); i++) { cout << "________________________________________" << endl; cout << "| " << Inventory[i] << endl; cout << "| 已携带物品 " << Inventory.size() << " / 10" << endl; cout << "|_______________________________________" << endl; } } if (input == "quit") { return 0; } } }
内容的提问来源于stack exchange,提问作者Maël Gagnon
相关产品推荐
相关产品推荐

