我目前正在学习2类编程(c ++),我们受命制作基于文本的rpg。我将此post用作库存系统的参考,因为我认为它非常有效。但是我一直遇到E0349“没有运算符“ ==”或“ <<”与这些操作符匹配“错误。
如果有人可以帮助我,那就太好了。这是我的全套代码:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <ostream>
#include <Windows.h>
#include <string>
#include <cctype>
using namespace std;
struct Item {
string name; //Item name.
int slot; //Head, Torso, Hands
int attack;
int knowledge;
int defense;
int hp;
int speed;
int charisma;
};
int main()
{
//Variables, Strings, etc.
int itemcounter = 0, counter = 0;
//"Empty" Item
Item Empty{ "<Empty>", 0, 0, 0 };
vector<Item> Equipment = { 6, Empty }; //Current Equipment, 6 empty slots.
vector<Item> Inventory = { }; //Player Inventory.
string InventorySlots[] = { "Head" "Torso", "Hands" }; //Player parts where items can be equiped.
cout << "You sit your bag down and take a look inside." << " You have:" << endl;
for (int i = 0; i < itemcounter; i++)
{
cout << InventorySlots[i];
if (Equipment[i] == "Empty ")
{
cout << " " << Equipment[i] << endl << endl;
}
}
}
这是我的错误更具体的地方
for (int i = 0; i < itemcounter; i++) //Display equipped
{
cout << InventorySlots[i];
if (Equipment[i] == "Empty ") //Error Here
{
cout << " " << Equipment[i] << endl << endl; //Errore Here
}
}
错误消息
Error (active) E0349 no operator "<<" matches these operands C:\Users\USER\source\repos\clunkinv\clunkinv\clunkinv.cpp 47
答案 0 :(得分:11)
Equipment[i]
是类型Item
的对象。如果您没有提供将对象与"Empty"
进行比较的方法,则编译器将不知道如何在行中进行比较
if (Equipment[i] == "Empty ")
比较属性
if (Equipment[i].name == "Empty ")
或者您必须提供一种方法。同样的问题
cout << " " << Equipment[i] << endl << endl;
编译器不知道如何打印对象。您必须为此提供功能。
您可以
struct Item {
string name; //Item name.
int slot; //Head, Torso, Hands
int attack;
int knowledge;
int defense;
int hp;
int speed;
int charisma;
};
std::ostream &operator<<(std::ostream &os, const Item& item) {
os << item.name;
return os;
}
如果要使用运算符,则必须为它们重载。