[英]Having difficulties making Inventory for my text based RPG game
So I created an Inventory class, wrote some codes and when I compiled the program I got this error:所以我创建了一个 Inventory 类,写了一些代码,当我编译程序时,我收到了这个错误:
no match for 'operator=' (operand types are 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' and 'Item*')| 'operator=' 不匹配(操作数类型是 'std::basic_ostream::__ostream_type {aka std::basic_ostream}' 和 'Item*')|
Here is the code:这是代码:
#include <iostream>
#include <vector>
#ifndef INVENTORY_H
#define INVENTORY_H
#include "Item.h"
using namespace std;
class Inventory
{
public:
Inventory(unsigned capacity = 10);
Inventory(const Inventory* other);
~Inventory();
Item **items;
unsigned totalItems;
unsigned capacity;
void initialize(const unsigned from = 0);
void expand();
void insertItem(const Item& item);
void removeItem(const unsigned index);
void clearInventory();
protected:
private:
};
#endif
#include "Inventory.h"
Inventory::Inventory(unsigned capacity)
{
this->capacity = capacity;
totalItems = 0;
items = new Item*[capacity];
initialize();
}
Inventory::Inventory(const Inventory* other)
{
this->capacity = other->capacity;
this->totalItems = other->totalItems;
this->items = new Item*[this->capacity];
initialize();
for(size_t i = 0; i < this->totalItems; i++)
{
cout << this->items[i] = new Item(*other->items[i]);
}
}
Can someone tell me what i did wrong?有人能告诉我我做错了什么吗?
Try this:尝试这个:
cout << (this->items[i] = new Item(*other->items[i]));
Looks like the << operator takes precedence in this case, so this expression is evaluated from left to right as:看起来在这种情况下 << 运算符优先,所以这个表达式从左到右计算为:
cout << this->items[i] // which is an ostream
then you try to assign that new Item()
to that ostream, so the = operator sees ostream on the left and *Item on the right.然后您尝试将该
new Item()
分配给该 ostream,因此 = 运算符在左侧看到 ostream,在右侧看到 *Item。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.