Вопрос

Hey in my text based adventure game. I have this class:

class wolves
{
    public:
    string name;
    int health;
private:
    string attack;
    //wolves(string name,int health); // Constructor
    //hitPoints() +1;
};

I have a method that randomaly counts hitpoints. I dont know how to create a function using a class. Or how to use the hitpoints function with the class.

Can anyone help?

hitpoints()

int hitPoints()
{
    srand(time(0)); // seed random number generator based on current time
int randomNumber= rand(); // generate random number
int hitPoints = (randomNumber% 20) + 1; // get a number between 1 and 20
return hitPoints;
}
int fatigue()
{
    srand(time(0)); // seed random number generator based on current time
int randomNumber= rand(); // generate random number
int fatigue = (randomNumber% 5) + 1; // get a number between 1 and 5
return fatigue;
}
int Encounter()
{


    srand(time(0)); // seed random number generator based on current time
    int randomNumber= rand(); // generate random number
    int encounter = (randomNumber% 3); // get a number between 1 and 5
    cin >> encounter;
        switch(encounter)
        {
        case 1:
            Wolves();
            menu = false;
            break;
        case 2:
            Soldier();
            break;
        case 3:
            CaveBear();
            break;
        }
        cout << encounter;

    return encounter;
}
Это было полезно?

Решение

To define a class member function, use the scope operator :: to qualify the name with the class name:

int wolves::hitpoints()
{
    return health;
}

This also works for functions inside structures and namespaces.

Of course, the function needs to first be declared inside the class body:

class wolves
{
public:
    string name;
    //wolves(string name,int health); // Constructor
    int hitPoints();
private:
    int health;
    string attack;
};

Also, for really short functions, it often makes more sense to define them inline inside the class definition:

class wolves
{
public:
    string name;
    //wolves(string name,int health); // Constructor
    int hitPoints() { return health; }
private:
    int health;
    string attack;
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top