Ошибка сегментации (ядро сброшено) во время работы моей программы, скомпилированной с g ++ - PullRequest
0 голосов
/ 20 мая 2018

В настоящее время я пишу свой большой проект для Uni.Я почти закончил большую часть этого, но в настоящее время я застрял на ошибке, которую я не уверен, как исправить.Каждый раз, когда я компилирую свой код с использованием g ++ и запускаю полученную программу, мне выдается сообщение об ошибке «Ошибка сегментации (дамп памяти)».

Мой друг сказал мне, что это может быть связано с тем, что мой плеер :: класс addItem использует строку, где она должна быть пустой.Однако, если я изменю это на void, мне также нужно будет изменить функцию в главном на void?Это исправит ошибку?

Это мой файл player.cpp:

#include "Player.h"
#include <iostream>
#include <string>
using namespace std;

Player::Player(){

}

void Player::setName(std::string myName){
    name = myName;
}

//Get the players name
std::string Player::GetName()
{
    return name;
}

//Add item to players inventory
std::string Player::AddItem(std::string item, int itemPrice)
{
    //Is players inventory not full?
    if (IsInventoryFull())
    {
        std::cout << "Inventory is full.";
    }

    else
    {
        //Can player afford item?
        if (goldCoins >= itemPrice)
        {
            goldCoins -= itemPrice;
            numbOfItems++;
            std::cout << "You have purchased " << item << "." << "\n";
            inventory.push_back(item); //Add item to inventory
            return item;
        }

        //If player cant afford item 
        else
        {
            std::cout << "You cannot afford this item." << "\n";
        }
    }
}

void Player::SellItem(int itemNum, int itemPrice)
{
    char response;
    std::cout << "Are you sure you want to sell: " << inventory[itemNum] << "? 'y' - Yes. 'n' - No." << "\n";
    std::cin >> response;

    switch (response)
    {
    case 'y':
        numbOfItems++;
        goldCoins += itemPrice;
        inventory.erase(inventory.begin() + itemNum);
        break;

    case 'n':
        std::cout << "That is ok." << "\n"; 
        break;

    default:
        std::cout << "Please enter correct data." << "\n";
    }
}




//Check to see if players inventory is full
bool Player::IsInventoryFull()
{
    //If players inventory isnt full
    if (numbOfItems < maxNumbItems)
    {
        return false;
    }

    //If players inventory is full
    else
    {
        return true;
    }
}

//Return size of players inventory
int Player::InventoryCapacity()
{
    return inventory.size();
}

//Get the players gold
int Player::GetGold()
{
    return goldCoins;
}

//List the players inventory
void Player::ListInventory()
{
    int itemNumb = 0; //item number in menu

    for (int i = 0; i < inventory.size(); i++)
    {
        itemNumb++;
        std::cout << itemNumb << ": " << inventory[i] << "\n";
    }

}

int Player::GetNumbOfItems()
{
    return numbOfItems;
}

Player::~Player()
{
}

Это моя основная функция (shop.cpp):

// Shop.cpp : Defines the entry point for the terminal (e.g. main)


#include "Player.h"
#include "ShopKeeper.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
    const int maxNumbItems = 5; //Maximum number of items that inventory can store
    int goldCoins = 150, //Amount of gold coins the player has
    numbOfItems = 0; //Number of con-current items player holds
    std::vector<std::string> inventory; //Players inventory
    std::string name = "Gorrex"; //Players name
    Player* player; //The player
    player->setName(name);
    ShopKeeper shopKeeper; //The shop keeper
    int response; //Menu navigation
    std::cout << "Greetings " << player->GetName() << ". Feel free to browse our exotic collectin of fruits." << "\n";
    std::cout << "1: Purchase Items. 2: Sell Items. 3: List Your Items. 4: Show Gold. 5: Exit" << "\n";

    do
    {
        std::cin >> response;

        switch (response)
        {
        case 1:
            shopKeeper.PurchaseItem(player);
            break;

        case 2:
            shopKeeper.SellItem(player);
            break;

        case 3:
            player->ListInventory();
            break;

        case 4:
            std::cout << "You have " << player->GetGold() << " gold coins." << "\n";
            break;

        case 5:
            std::cout << "Thank you for shopping." << "\n";
            break;

        default:
            std::cout << "Please enter valid data." << "\n";
            std::cout << "1: Purchase Items. 2: Sell Items. 3: List Your Items. 4: Show Gold. 5: Exit" << "\n";
        }

        std::cout << "1: Purchase Items. 2: Sell Items. 3: List Your Items. 4: Show Gold. 5: Exit" << "\n";

    } while (response != 5);


    //Keep window open
    std::string barn;
    std::cin >> barn;
    return 0;
}

СледуетЯ делаю пустую переменную IsInventoryFull и вызываю ее вместо строковой версии «Inventory is full»?

Код, использующий указатели:

#include "ShopKeeper.h"
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;

//Player purchases item from shop keeper
void ShopKeeper::PurchaseItem(Player* player)
{
    //Player player;

    int response = 0; //Menu navigation
    std::cout << "1: Orange - 30 gold. 2: Apple - 50 gold. 3: Lemon - 10 gold. 4: Dragon Fruit - 75 gold. 5: Mandarin - 25 gold." << "\n";

    do
    {
        std::cin >> response;

        switch (response)
        {
        case 1:
            player->AddItem("Orange", 30);
            break;

        case 2:
            player->AddItem("Apple", 50);
            break;

        case 3:
            player->AddItem("Lemon", 10);
            break;

        case 4:
            player->AddItem("Dragon Fruit", 75);
            break;

        case 5:
            player->AddItem("Mandarin", 25);
            break;

        default:
            std::cout << "Please enter valid data." << "\n";
            std::cout << "1: Orange - 30 gold. 2: Apple - 50 gold. 3: Lemon - 10 gold. 4: Dragon Fruit - 75 gold. 5: Mandarin - 25 gold." << "\n";
        }
    } while (response > 5 || response < 1);

}

//Shop  keeper sells item to player
void ShopKeeper::SellItem(Player* player)
{
    //Player player;
    int response = 0;
    player->ListInventory();
    if (response < player->GetNumbOfItems())
    {
        std::cin >> response;

        switch (response)
        {
        case 1:
            player->SellItem(0, 20);
            break;

        case 2:
            player->SellItem(1, 20);
            break;

        case 3:
            player->SellItem(2, 20);
            break;

        case 4:
            player->SellItem(3, 20);
            break;

        case 5:
            player->SellItem(4, 20);
            break;

        default:
            std::cout << "Please enter valid data." << "\n";
            player->ListInventory();
        }
    }

    else
    {
        std::cout << "Item doesn't exist."; 
    }

}

ShopKeeper::ShopKeeper()
{
}


ShopKeeper::~ShopKeeper()
{
}
...