首页 > 解决方案 > 如何将值从类返回到主

问题描述

我正在尝试建立一个简单的地牢爬行并陷入战斗。承受的伤害正在发挥作用,但我无法返回新的健康值,使其低于初始化值。每次 l;oop 重复时,它都会返回初始值。宝物也是一样。是什么赋予了?如何将成员函数中的值返回给 main?

#include <iostream>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;

class monster
{
public:
    int fight()
    {

    }
};

class chest
{
    int loot()
    {

    }
};

class movement
{
public:
    char wasd()
    {
        char mv;
        char up = 'w';
        char left = 'a';
        char right = 'd';
        char down = 's';

        cout << "\nMove using w for (up), a for (left), d for (right), and s for (down).\n\n";
        mv = _getch();

        if (mv == up)
        {
            cout << "You have moved up 1 space.\n";
        }
        else if (mv == left)
        {
            cout << "You have moved left 1 space.\n";
        }
        else if (mv == right)
        {
            cout << "You have moved right 1 space.\n";
        }
        else if (mv == down)
        {
            cout << "You have moved down 1 space.\n";
        }
        else
        {
            cout << "it didn't work.";

        }
        return 0;
    }
};

class random_enc
{   public:
    int treasure;
    int health = 12;
    public:
    int encounter(int)
    {
        int randnumber = rand() % 5 + 1;
        treasure = 0;
        if (randnumber == 1)
        {
            cout << "You have been attacked!!! You lose 1 hitpoint." << endl;
            health = --health;
            cout << "Hitpoints remaining: " << health << endl;
            return health;
        }
        else if (randnumber == 2)
        {
            cout << "You found treasure!" << endl;
            treasure = ++treasure;
            cout << "Treasure collected: " << treasure << endl;;
            return random_enc::treasure;
        }
        else if (randnumber == 3)
        {
            return health;
        }
        else if (randnumber == 4)
        {
            cout << "You step on a trap and take damage!! You lose 1 hit point.\n" << "Good bye." << endl;
            health = --health;
            cout << "Hitpoints remaining: " << health << endl;
        }
        return health;
    }
};



int main()
{
    string name;

    cout << "Welcome to the dungeon, enter your name:\n";
    cin >> name;
    cout << "\nGood luck in the dungeon " << name << "\n";
    int health = 12;

    while (health != 0)
    {
        movement mvmt;
        random_enc random;
        mvmt.wasd();

        random.encounter(health);
    }
    cout << "You have been killed. Goodbye.\n";
    return 0;
}

标签: c++functionclassreturn

解决方案


我替换了 random_enc 中遇到函数的参数 health。我用一个指针替换它: void meet (int& health) 这会传递引用而不是值。然后在成员函数中定义健康。

#include <iostream>
using namespace std;

void encounter(int& health)  // note the ampersand
{
    --health; // this will change health in main
}

int main()
{
    int health = 12;
    encounter(health);
    cout << health << '\n';  // prints 11
}

推荐阅读