поиск связанного списка в C ++ - PullRequest
0 голосов
/ 04 мая 2020

каждый

Я работаю над RPG-игрой как над классным проектом. A linked list используется для инвентаря. Я пытаюсь добавить функцию поиска, поскольку хочу, чтобы пользователь мог продавать инвентарь.

В идеале searchItem(string name) берет указанное имя элемента и просматривает список, находя соответствующий элементу, затем обратный адрес товара. Однако при вызове функции среда IDE выдает ошибку EXC_BAD_ACCESS(code=1, adress0x44).

Я полагаю, что она не возвращает правильный адрес, но с моей текущей способностью я не могу найти решение.

Любая помощь будет по достоинству оценена.

Inventory.hpp

#include <stdio.h>
#include <list>
#include <iostream>
#include "Item.hpp"
using namespace std;
class Inventory{
private:
    struct Inven{
        Item item;
        struct Inven *next = nullptr;
    };

    Inven *head;

public:
    Inventory();
    ~Inventory();

    void appandItem(Item obj);
    void insertItem(Item obj);
    void deleteItem(string name, int qt);
    void displayInventory();
    Item* searchItem(string name);
};

Inventory. cpp Я только разместил функцию searchItem, потому что другие работают нормально

Item* Inventory::searchItem(string name){
    //  to go through the inventory
    Inven *itemPtr = nullptr;
    //  to point to the previous item
    Inven * previousItem = nullptr;

    //  if the invnetory is empty, nothing happands
    if(!head)
        return nullptr;

    //  determine if the first item is the one.
    if(head->item.getName() == name){
        //  if so, return the address of item
        return &itemPtr->item;

    }else{
        //  Initialize itemPtr to head of inventory
        itemPtr = head;

        //  skip all items whose name is not match
        while (itemPtr != nullptr && itemPtr->item.getName() != name){
            previousItem = itemPtr;
            itemPtr = itemPtr->next;
        }
        //  return the address found
        if (itemPtr){
            return &itemPtr->item;
        }
    }
    return nullptr;
}

вот код, по которому вызывается searchItem, не может получить доступ к getSellValue (), который определен в Item class

#include "Shop.hpp"

//  sell inventory for gold
int Shop::sell(Inventory inventory, string itemName, int qt){
    this->goldEarned = inventory.searchItem(itemName)->getSellValue() * qt;
    inventory.deleteItem(itemName, qt);
    return this->goldEarned;
}

Дайте мне знать, если нужна дополнительная информация.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...