c++ - 在为基于文本的RPG游戏制作 list 时遇到困难

标签 c++

因此,我创建了一个 list 类,编写了一些代码,并且在编译程序时遇到了以下错误:

与'operator ='不匹配(操作数类型为'std::basic_ostream::__ ostream_type {aka std::basic_ostream}'和'Item *')|

这是代码:

Inventory.h文件

#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

Inventory.cpp文件
#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]);
    }
}

有人可以告诉我我做错了吗?

最佳答案

试试这个:

 cout << (this->items[i] = new Item(*other->items[i]));

在这种情况下,看上去<< <<运算符具有优先权,因此该表达式从左到右的计算方式为:
cout << this->items[i]    // which is an ostream

那么您尝试将new Item()分配给该ostream,因此=运算符将在左侧看到ostream,在右侧看到* Item。

关于c++ - 在为基于文本的RPG游戏制作 list 时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59970701/

相关文章:

c++ - 通过引用将对象参数传递给仿函数

c++ - 尝试将 SDL 2 与 Visual Studio c++ 一起使用

c++ - 错误 : request for member '..' in 'this' , 是非类类型 '--* const'

c++ - 初始化继承的成员数据

c++ - 是否可以在其范围之外访问局部变量的内存?

c++ - OpenCL "multithreading"示例

c++ - 在 C++ 中创建 Windows 窗体应用程序(不带 .NET)

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

C++11 std::generate 和 std::uniform_real_distribution 调用两次给出了奇怪的结果

c++ - 过程在 mysql workbench 中有效,但不适用于 C++ 连接器