类对象未在范围中声明



我目前正在遇到一个问题,我似乎无法围绕发生这种情况。在我的(Unsplit(程序中,我创建了一个定义实体对象的类,并且能够处理其创建和变量(正如我在添加

之前已经测试的那样(
std::string getName(Entity)const;
std::string getType(Entity)const;
int getDamage(Entity)const;
int getHealth(Entity)const;

,但是当我这样做...即使它们已经在班上公开声明,我也能够完全呼叫initialize((;攻击((;和printStats((;很好,它看不到其他四个,因此无法被调用。

#include <iostream>
#include <string>
#include <math.h>
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
using namespace std;
class Entity
{
public:
    Entity() { // default constructor
        name = "Human";
        type = "Normal";
        damage = 1;
        health = 100;
    }
    void printStats();
    void Initialize(string, string, int, int); //transformer or setting function
    void Attack(Entity&); //observer or getter function
    std::string getName(Entity)const;
    std::string getType(Entity)const;
    int getDamage(Entity)const;
    int getHealth(Entity)const;
private://data members and special function prototypes
    std::string name;
    std::string type;
    int damage;
    int health;
};
void summonEnemy(Entity&);
int main () {
    /* initialize random seed: */
    srand (time(NULL));
    Entity  Player;//declaring new class objects
    Entity  Enemy;//declaring new class objects
    Player.Initialize("Player", "Normal", 10, 90);
    summonEnemy(Enemy);
    return 0;
}
void summonEnemy(Entity &target) {
    target.Initialize("Enemy", "Normal", floor(rand() % 20 + 1), floor(rand() % 100));
   cout << "An " << getType(target) << " type " << getName(target) << " has appeared with " <<
        getHealth(target) << "HP and can do " << getDamage(target) << " damage.";
}

错误消息:

error:'getType' Was not defined in this scope.
error:'getName' Was not defined in this scope.
error:'getHealth' Was not defined in this scope.
error:'getDamage' Was not defined in this scope.

切断一些代码以将其缩小范围,以便仅可能出现问题的原因...但是说实话,这可能是我看不到的简单的东西。任何帮助。

您没有正确调用它们。他们是Entity类的成员,而不是独立函数。从它们中删除Entity参数,因为它们已经具有隐式Entity *this参数,然后以这样的方式调用它们:

class Entity
{
public:
    Entity(); // default constructor
    ...
    std::string getName() const;
    std::string getType() const;
    int getDamage() const;
    int getHealth() const;
    ...
};

Entity::Entity()
{
    Initialize("Human", "Normal", 1, 100);
}
std::string Entity::getName() const
{
    return name;
}
std::string Entity::getType() const
{
    return type;
}
int getDamage() const
{
    return damage;
}
int getHealth() const
{
    return health;    
}

void summonEnemy(Entity &target)
{
    target.Initialize("Enemy", "Normal", floor(rand() % 20 + 1), floor(rand() % 100));
    cout << "An " << target.getType() << " type " << target.getName() << " has appeared with " <<
        target.getHealth() << "HP and can do " << target.getDamage() << " damage.";
}

getTypeEntity的成员函数,因此您需要在Entity对象上调用它:

target.getType();

在班上,您可以将其实现为:

class Entity {
    ...
    std::string getType() const { return type; }
    ...
};

您的其他三个播放器也是如此。

最新更新