【发布时间】:2021-06-19 11:20:38
【问题描述】:
这里我的类的私有部分中有一个数组,它无法保留在类的不同成员中设置的值;在战斗序列中,数组中的两个值都等于 0。
#include <iostream>
#include <string>
#include<math.h>
#include<cstdlib>
using namespace std;
class champions {
private:
int health_array[2] = { };
int attack_array[2] = { };
public:
void health_attack_set() {
int health_set{};
int attack_set{};
for (int i = 0; i < 2; i++) {
health_array[i] = health_set;
attack_array[i] = attack_set;
}
}
void fight_sequence(int random_champion, int random_opponent) {
cout << "FIGHT\n\n";
while (health_array[random_champion] > 0 or health_array[random_opponent] > 0) {
(health_array[random_opponent] -= attack_array[random_champion]);
if (health_array[random_opponent] <= 0) {
break;
}
(health_array[random_champion] -= attack_array[random_opponent]);
}
if (health_array[random_champion] > 0) {
cout << "CHAMPION 1 WINS!!!";
}
if (health_array[random_opponent] > 0) {
cout << "CHAMPION 2 WINS!!!";
}
if (health_array[random_champion] == 0 && health_array[random_opponent] == 0) {
cout << "NO ONE WINS!!";
}
}
void champion_1() {
health_attack_set();
health_array[0] = 400;
attack_array[0] = 150;
}
void champion_2() {
health_attack_set();
health_array[1] = 500;
attack_array[1] = 100;
}
};
int main() {
champions fight;
fight.fight_sequence(0, 1);
return 0;
}
我相信这可能是一个简单的错误,但很难发现;感谢您提供的任何帮助。
【问题讨论】:
-
“无法保留不同对象中设置的值”中的“不同对象”在哪里?
-
你在哪里打电话给
champion_1()或champion_2()? -
champion_1 和 Champion_2 是不同的对象。我在这些对象中设置的值不会在对象外部处理,例如:(health_array[0] = 400)。
-
你需要阅读一本关于 C++ 的基础教科书。您的代码只有一个
champions类型的对象(在main()中创建)。虽然您认为champion_1()或champion_2()是对象,但没有人可以帮助您。 -
这个结构就是麻烦。
champions应该是class champion,就像std::vector<champion>一样,其中每个英雄都有自己的属性。您在这里所做的几乎完全忽略了对象的意义。
标签: c++ arrays function class private