c++ - 将对象从堆栈移动到数组 C++

标签 c++

嘿伙计们,我正在写一些类(class)作业,我快完成了,在我的代码中,我为玩家创建了一个宝箱和一个袋子。当向玩家展示箱子中的元素时,他们被要求保留这些元素,然后将其存放在袋子中或丢弃这些元素。

在测试我的代码时,我注意到向玩家显示的元素并不是随后存储在袋子中的元素,几乎就像袋子是从看不见的堆栈中取出的一样。然后最后,当我调用玩家包时,它仍然显示为空,好像没有存储任何元素???

请有人告诉我哪里出了问题以及如何解决它???

这些是导致错误的代码的特定部分:

    void PrintTreasureChest()
{
    //TreasureChest A;
    int j;
    for (j = 1; j < 5; j++)
    {
        cout << "Item " << j << " in your chest is: " << endl;
        cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
        cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
        cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
        cout << " " << endl;
        PlayerChoice(A);
        TreasureChest().Chest.pop();
        cout << " " << endl;
    }
    cout << " " << endl;
    cout << "This chest is now empty" << endl;
    cout << " " << endl;
    cout << " " << endl;
    cout << "Items in bag: " << endl;
    //Game().ShowRucksack();
    return;

}

void PlayerChoice()
{
    char Answer;
    cout << "If you want to keep the item press Y" << endl;
    cout << "If you want to discard the item press N" << endl;
    cin >> Answer;
    while (Answer == 'Y' || Answer == 'y')
    {
        cout << "Item stored in your bag" << endl;
        StoreItem();
        return;
    }
    while (Answer == 'N' || Answer == 'n')
    {
        cout << "Item was discared from the Treasure Chest" << endl;
        return;
    }
    while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
    {
        cout << "To decide press Y for accept OR press N for Decline" << endl;
        cin >> Answer;
        if (Answer == 'Y' || Answer == 'y') {
            cout << "Item stored in your bag" << endl;

            //store item in bag
            return;
        }
        else (Answer == 'N' || Answer == 'n'); {
            cout << "Item was discared from the Treasure Chest" << endl;
            return;
        }
        return;
    }
}

void StoreItem()
{
    int dim = 10;
    int P = index(Rucksack, dim);
    Rucksack[P] = A.Chest.top();
    cout << "Item placed in your Bag: " << Rucksack[P].Name << endl;
    return;
}

这是完整的代码:

// Loot Class v11.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <vector>
#define LootNumber 14
using namespace std;

// the 3 arrays initialise the 3 stats of each item
string NameOption[] = { "Stone", "Leather Gloves", "Dragon Gauntlets", "Chair Leg", "Dragon Scale Helmet", "Pebble", "Rusted Breastplate", "Dragon Breastplate", "Empty Bottle", "Chainmail Trousers", "Dragon Skin Trousers", "Broken Stick", "Dagger", "Dragons Sword" };
int RarityOption[] = { 0, 1, 3, 0, 3, 0, 2, 3, 0, 2, 3, 1, 2, 3 };
bool SetOption[] = { 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 };

// this class is grouping Name, Rarity and Set. Resulting in every Loot object made, contains 3 variables
class Loot
{
public:
    string Name;
    int Rarity;
    bool Set;

    // constructor initialises each of the feilds
    Loot(string N, int R, bool S)
    {
        Name = N;
        Rarity = R;
        Set = S;

    }
    // default constructor
    Loot()
    {
        Name = "Empty";
        Rarity = 0;
        Set = false;
    }
    // Prints a randomly selected item of loot to the screen, used to check randomisation and that all loot variables print in the correct order
    void PrintLoot()
    {
        int i = rand() % LootNumber;
        Loot A(NameOption[i], RarityOption[i], SetOption[i]);
        cout << "Loot item: " << A.Name << endl;
        cout << "Rarity out of 3: " << A.Rarity << endl;
        cout << "Part of set: " << A.Set << endl;
    }

};
// enables the creation of a container to stack  Loot items in
class TreasureChest
{
public:
    stack<Loot> Chest;

    // stacks 4 random items in the chest
    TreasureChest()
    {
        int i = rand() % LootNumber;
        int j = rand() % LootNumber;
        int k = rand() % LootNumber;
        int h = rand() % LootNumber;

        Chest.push(Loot(NameOption[j], RarityOption[j], SetOption[j]));
        Chest.push(Loot(NameOption[k], RarityOption[k], SetOption[k]));
        Chest.push(Loot(NameOption[i], RarityOption[i], SetOption[i]));
        Chest.push(Loot(NameOption[h], RarityOption[h], SetOption[h]));
    }

    // prints full contents of Treasure Chest to screen
    void ShowFullChest()
    {
        int i;
        for (i = 1; i < 5; i++)
        {
            cout << "Item: " << i << endl;
            cout << "Name:" << TreasureChest().Chest.top().Name << endl;
            cout << "Rarity out of 3: " << TreasureChest().Chest.top().Rarity << endl;
            cout << "Part of a set: " << TreasureChest().Chest.top().Set << endl;
            TreasureChest().Chest.pop();
        }
    }

};

// Creates container for player to store their chosen Loot items
class PlayerRuckSack
{
public:
    Loot Rucksack[10];

    // default constructor initialising each array 
        PlayerRuckSack()
    {
        for (int i = 0; i < 10; i++)
        {
            Rucksack[i] = { "Empty", 0, false };
        }
    };

    // prints contents of a rucksack to the screen to allow the player to see what they have collected
    void ShowRucksack()
    {
        for (int i = 0; i < 10; i++)
        {
            cout << Rucksack[i].Name << " " << Rucksack[i].Set << " " << Rucksack[i].Rarity << " " << endl;
        }
    }

    // replaces an each array with items of Loot and prints when all arrays have been replaced
    int index(Loot x[], int n)
    {
        int i = 0;
        int index;
        while (x[i].Name != "empty" && 0 && false && i < n)
        {
            i++;
            index = i;
            return index;
        }
        while (i == n)
        {
            cout << "BAG FULL" << endl;
        }
    }

};

// For runing the game
class Game : public PlayerRuckSack
{
public:
    string PlayerName;
    TreasureChest A;


    Game()
    {
        PlayerName = "User 1";
    }

    Game(string U)
    {
        PlayerName = U;
    }
    // intro message to start game
    void StartGame()
    {
        cout << "Welcome to the Cave of Luck" << endl;
        cout << "What is your name brave warrior" << endl;
        cin >> PlayerName;
        cout << PlayerName << " There are 3 Treasure Chests in this cave" << endl;
        cout << "Treasure Chests contain many different items" << endl;
        cout << "However it appears your bag is small and can only hold 10 items in total" << endl;
        cout << "Choose wisley " << PlayerName << endl;
        cout << "Good Luck!!" << endl;
        cout << " " << endl;
        cout << " " << endl;
    }

    //Gives player choise whether to keep or discard each loot item 
    void PlayerChoice()
    {
        char Answer;
        cout << "If you want to keep the item press Y" << endl;
        cout << "If you want to discard the item press N" << endl;
        cin >> Answer;
        while (Answer == 'Y' || Answer == 'y')
        {
            cout << "Item stored in your bag" << endl;
            StoreItem();
            return;
        }
        while (Answer == 'N' || Answer == 'n')
        {
            cout << "Item was discared from the Treasure Chest" << endl;
            return;
        }
        while (Answer != 'y' || Answer != 'Y' || Answer != 'N' || Answer != 'n')
        {
            cout << "To decide press Y for accept OR press N for Decline" << endl;
            cin >> Answer;
            if (Answer == 'Y' || Answer == 'y') {
                cout << "Item stored in your bag" << endl;

                //store item in bag
                return;
            }
            else (Answer == 'N' || Answer == 'n'); {
                cout << "Item was discared from the Treasure Chest" << endl;
                return;
            }
            return;
        }
    }
    // Prints the top of TreasureChest to the screen plus uses Playerchoise() after each item is shown
    void PrintTreasureChest()
    {
        //TreasureChest A;
        int j;
        for (j = 1; j < 5; j++)
        {
            cout << "Item " << j << " in your chest is: " << endl;
            cout << "Name:" << (TreasureChest().Chest.top()).Name << endl;
            cout << "Rarity out of 3: " << (TreasureChest().Chest.top()).Rarity << endl;
            cout << "Part of a set: " << (TreasureChest().Chest.top()).Set << endl;
            cout << " " << endl;
            PlayerChoice(A);
            TreasureChest().Chest.pop();
            cout << " " << endl;
        }
        cout << " " << endl;
        cout << "This chest is now empty" << endl;
        cout << " " << endl;
        cout << " " << endl;
        cout << "Items in bag: " << endl;
        //Game().ShowRucksack();
        return;

    }
    // informs player another chest is coming 
    void NextChest()
    {
        cout << "Your next chest contains: " << endl;
        cout << " " << endl;
    }
    // Prints end Game message
    void EndGame()
    {
        cout << " " << endl;
        cout << " " << endl;
        cout << "You have opened all the Chests, come back soon to the Cave of Treasures" << endl;
        cout << " THANKYOU FOR PLAYING" << endl;
    }

    void StoreItem()
    {
        int dim = 10;
        int P = index(Rucksack, dim);
        Rucksack[P] = A.Chest.top();
        cout << "Item placed in your Bag: " << Rucksack[P].Name << endl; //B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;
        return;
    }
};




int main()
{
    Game A;
    //TreasureChest A;
    PlayerRuckSack B;
    //A.StartGame();
    srand(time(NULL));
    A.PrintTreasureChest();
    for (int i = 0; i < 10; i++)
    {
        cout << B.Rucksack[i].Name << " " << B.Rucksack[i].Set << " " << B.Rucksack[i].Rarity << " " << endl;
    }
    //A.NextChest();
    A.EndGame();

    //TreasureChest A;
    //PlayerRuckSack B;
    //int dim = 10;
    //int P = index(B.Rucksack, dim);
    //B.Rucksack[P] = A.Chest.top();
    //cout << "Item in your Bag " << B.Rucksack[P].Name <<  B.Rucksack[P].Set << B.Rucksack[P].Rarity << endl;

    //cout << P << endl;

    return 0;
}

最佳答案

我知道为什么你的背包中没有存储任何内容

int index(Loot x[], int n)
{
    int i = 0;
    int index;
    while (x[i].Name != "empty" && 0 && false && i < n)
    {
        i++;
        index = i;
        return index;
    }
    while (i == n)
    {
        cout << "BAG FULL" << endl;
    }
}

仔细看看这一行:

while (x[i].Name != "empty" && 0 && false && i < n)

&& 0 && false0false 都表示这始终为 false,并且无论如何,Rucksack 都会被报告为空。

然后代码将从 index() 的底部掉出,而不返回值。 之后程序行为是未定义的,因为您使用了未返回的返回值。此后可能会发生任何疯狂的事情。

如果您无法解决其他问题,请解决该问题并提出另一个问题。 目前还有些模糊。

关于c++ - 将对象从堆栈移动到数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43746457/

相关文章:

c++ - 重载 vector 下标运算符取一个 char * 或 string

C++ 提取字符串

c++ - 大型 PCIe DMA Linux x86-64

c++ - 不使用预处理器调用 Clang

c++ - 如何将未知大小的字符串从 DLL 返回到 Visual Basic

c++ - C++文字中的分隔符十和单位

c++ - new 运算符在汇编中返回什么?

c++ - C++把静态成员变量放在什么地方,栈中还是数据段中

c++ - 在 C++ 中,什么样的语句不需要分号终止?

c++ - 用于指针生成的递归模板