C ++ установка значения для элемента enum внутри класса - PullRequest
0 голосов
/ 18 сентября 2018

меня зовут Джош, и я пытаюсь заставить этот код работать, но пока ничего не могу достичь ... Извините, если это глупо и я трачу ваше время, я новичок в C ++ (который я уже люблю),Позвольте мне попытаться объяснить.

По сути, я хочу вставить перечисление в класс, установить значение в iten из перечисления (возможно, в классе), но я не могу получить доступ к элементу для установкизначение ...

например.Edge of Fight - 24 ед. Физического урона / 54 скорости передвижения / 5 сил способности.Извините за плохой английский, это не мой основной язык ...

#include <iostream>

using namespace std;






class Enemy {
protected:
    int physicalDamage;
    double moveSpeed;
    int abilityPower;
public:
    void setPhysicalDamage(int p) {
        physicalDamage = p;
    }
    void setMoveSpeed(int m) {
        moveSpeed = m;
    }
    void setAbilityPower(int ap) {
        abilityPower = ap;
    }

    virtual void attack() = 0;
    virtual void ability() = 0;
    virtual void speed() = 0;


};

class Itens: public Enemy {
protected:
    enum class itensID {
        gunnersBreaker,
        hitswamSword,
        fineshotsWrath,
        banesBook,
        infinityStar,
        edgeOfFight,
    };

    itensID iID;
public:

    void setItensID(int r) {

        iID.edgeOfFight = r; // Gives me error, I don't really know a way                 around that... 
    };                      // But basically what I wanna do is marked in     double slashes...
                           // I don't know if I should use pointers for     that, but I tried and it also didn't work...



};

class Ninja : public Enemy {
public:
    void attack() {
        cout << "Hero: Ninja." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

class Monster : public Enemy {
public:
    void attack() {
        cout << "Hero: Monster." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

int main() {
    Ninja n;
    Monster m;
    Enemy *e1 = &n;
    Enemy *e2 = &m;

    /*

        Find a way to set an enum item to the Ninja hero

                                                            */

    e1->setPhysicalDamage(203);
    e1->setAbilityPower(12);
    e1->setMoveSpeed(321.32);
    e2->setPhysicalDamage(40);
    e2->setAbilityPower(654);
    e2->setMoveSpeed(310.44);

    n.attack();
    n.ability();
    n.speed();
    m.attack();
    m.ability();
    m.speed();
}

Я обновил код, но получил сообщение об ошибке, что я ломаю голову, пытаясь это исправить.Я объясню, что я пытаюсь сделать сейчас.

Я хочу, чтобы проблема обновила текущий pd, ap, ms Hero с добавлением элемента gunnersBreak

ОБНОВЛЕННЫЙ КОД!

#include <iostream>
#include <string>

using namespace std;



struct itensID {
    void gunnersBreaker(int pd, int ap, float ms);
    void hitswamSword(int pd, int ap, float ms);
    void fineshotsWrath(int pd, int ap, float ms);
    void banesBook(int pd, int ap, float ms);
    void infinityStar(int pd, int ap, float ms);
    void edgeOfFight(int pd, int ap, float ms);
};


void itensID::gunnersBreaker(int pd, int ap, float ms)
{
    int physicalDamage = pd;
    int abilityPower = ap;
    float moveSpeed = ms;

    cout << "\n Shotgun: Gunner's Break " << endl;
    cout << "\n Stats:";
}

void itensID::hitswamSword(int pd, int ap, float ms)
{
}

void itensID::fineshotsWrath(int pd, int ap, float ms)
{
}

void itensID::banesBook(int pd, int ap, float ms)
{
}

void itensID::infinityStar(int pd, int ap, float ms)
{
}

void itensID::edgeOfFight(int pd, int ap, float ms)
{
}



class Enemy {
protected:
    int physicalDamage;
    int abilityPower;
    float moveSpeed;

public:
    void setEnemyStatus(int p, int a, float m) {
        physicalDamage = p;
        abilityPower = a;
        moveSpeed = m;
    }

    virtual void attack() = 0;
    virtual void ability() = 0;
    virtual void speed() = 0;


};

                             // Basically what I wanna do now is, add two or     three values to the items eg. gunnersBreaker (int pd, int ap & float ms)
                            // Since I am struggling to get this going, I     have decided to set them as string, just to print while I figure-
                           // out how to add multiple values for a item in a     structure, maybe I should make them a void function instead-
                          // of a regular variable? (I would discard this     since regular variables takes only one identifier, I guess)
                         //  or should I make it a class instead?



class Ninja : public Enemy {
public:
    void attack() {
        cout << "Hero: Ninja." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

class Monster : public Enemy {
public:
    void attack() {
        cout << "Hero: Monster." << endl;
        cout << "Physical Damage:  " << physicalDamage << endl;
    }
    void ability() {
        cout << "Ability Power: " << abilityPower << endl;
    }
    void speed() {
        cout << "Movement Speed: " << moveSpeed << endl;
    }
};

int main() {
    Ninja n;
    Monster m;
    Enemy *e1 = &n;
    Enemy *e2 = &m;
    itensID iID;

    /*
        on the lines below ptr1 and ptr2, I got kind of an error, 
        I got to find a way to calculate the Enemy Status with the addition     of the item specs
        and print out the item I am using, EG. Hero: Ninja!
                                             Weapon: Gunner's Breaker.
                                             Stats.... and so on...
                                                                                            */

    e1->setEnemyStatus(35,10,310.21) + iID.gunnersBreaker(33,11,32.32); //     ptr1
    e2->setEnemyStatus(54,65,235.30);                                  //     ptr2

    n.attack();
    n.ability();
    n.speed();
    m.attack();
    m.ability();
    m.speed();
}

1 Ответ

0 голосов
/ 18 сентября 2018

Это потому, что вы пытаетесь использовать enum как struct и присваивать значение одному из его элементов.enums - это список именованных значений, которые могут использоваться для представления некоторых значений (например, флагов или состояний), которые неудобно и / или небезопасно представлять арифметическими типами.itensID iID - это переменная вашего класса перечисления itensID, поэтому вы можете присвоить ей одно из именованных значений, перечисленных в itensID теле класса перечисления (т. Е. iID = itensID::edgeOfFight).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...