我目前遇到一个问题,我似乎无法理解为什么会发生这种问题。 在我的(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.
切断一些代码以缩小范围,以便只显示可能导致问题的原因......但老实说,这可能是我看不到的简单事情。任何帮助表示赞赏。
答案 0 :(得分:2)
getType
是Entity
的成员函数,因此您需要在Entity
对象上调用它:
target.getType();
在课堂上,您可以将其实现为:
class Entity {
...
std::string getType() const { return type; }
...
};
对于其他三位制定者来说也是如此。
答案 1 :(得分:2)
您没有正确地调用它们。他们是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.";
}