c++ - 如何将值从类返回到主
问题描述
我正在尝试建立一个简单的地牢爬行并陷入战斗。承受的伤害正在发挥作用,但我无法返回新的健康值,使其低于初始化值。每次 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;
}
解决方案
我替换了 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
}
推荐阅读
- json - 在 React SharePoint 框架 Web 部件中解决 Promise 后 JSON 数据发生变化
- swift - 如何重新加载具有编辑更改的 CloudKit 单元格
- c# - RegularExpressionValidator ValidationExpression 不匹配
- xamarin - 视图已添加 u AddSubview 未在 UI 中显示(Mac OS Mojave)
- vb.net - 显示一个最小化的、动态创建的表单
- javascript - 如何从两个相同的 Web 表单中的任何一个提交?
- vue.js - 将 sigma 导入 vuejs + webpack 项目
- alexa - 亚马逊如何为 Alexa 选择第一方技能
- python - 如何在多级索引中为某些列(但不是全部)交换级别
- javascript - 带有 DataTable.net 数据表的 ASP.Net Core 2.1 不显示任何数据