我目前遇到一个问题,我似乎无法理解它为什么会发生。 在我的 (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.";
}
关于c++ - 未在范围内声明的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012253/