首页 > 解决方案 > 使用私有访问说明符中的数组

问题描述

在这里,我的类的私有部分中有一个数组,它无法保留在类的不同成员中设置的值;在战斗序列中,数组中的两个值都等于 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;
}

我相信这可能是一个简单的错误,但很难发现;感谢您提供的任何帮助。

标签: c++arraysfunctionclassprivate

解决方案


我认为您的问题来自于不了解如何在存在类和多个对象的情况下构造代码。我以更简洁和更常见的方式重组了您的代码(这不是唯一的方法,但它更典型)。希望没有错别字。

#include <iostream>
#include <string>
#include<math.h>
#include<cstdlib>

using namespace std;

class Champion{
public:
    int health;
    int attack;

    Champion(int health_, int attack_) : health(health_), attack(attack_) {
    }
};

void fight_sequence(Champion& champion, Champion& opponent) {
    cout << "FIGHT\n\n";
    while (champion.health > 0 || opponent.health > 0) {
        (opponent.health -= champion.attack);
        if (opponent.health <= 0) {
            break;
        }
        (champion.health -= opponent.attack);
    }
    if (champion.health > 0) {
        cout << "CHAMPION 1 WINS!!!";
    }
    if (opponent.health > 0) {
        cout << "CHAMPION 2 WINS!!!";
    }
    if (champion.health == 0 && opponent.health == 0) {
        cout << "NO ONE WINS!!";
    }
}

int main() {
    Champion champion_1(400, 150);
    Champion champion_2(500, 100);

    fight_sequence(champion_1, champion_2);
    return 0;
}

推荐阅读