0

嘿,在我的基于文本的冒险游戏中。我有这堂课:

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

我有一种随机计算生命值的方法。我不知道如何使用类创建函数。或者如何在类中使用 hitpoints 函数。

任何人都可以帮忙吗?

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;
}
4

1 回答 1

2

要定义类成员函数,请使用范围运算符::将名称限定为类名:

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

这也适用于结构和命名空间内的函数。

当然,函数需要先在类体内声明:

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

此外,对于非常短的函数,在类定义中内联定义它们通常更有意义:

class wolves
{
public:
    string name;
    //wolves(string name,int health); // Constructor
    int hitPoints() { return health; }
private:
    int health;
    string attack;
};
于 2012-10-07T17:18:49.450 回答