我正在尝试制作一个简单的游戏
会发生什么事,就是玩家会被各种物体击中,从而导致生命值的增加/减少。
mainGame();创建只是为了查看其是否正常工作。
在编译时我得到了
(.text$_ZN5gamer7setDataEv[__ZN5gamer7setDataEv]+0x117)||undefined reference to `gamer::mainGame()'|
我尝试了friend
关键字,但这给了我未定义引用对象的错误
class gamer
{
public:
string gName;
int gHealth;
int continueGame;
void mainGame();
void setData()
{
cout << "Enter your name " <<endl;
cin >> gName;
srand(time(0));
gHealth = 100 + (rand()%200);
cout << gName << " has health of " << gHealth << endl;
cout << "Would you like to continue ? 0 for yes" << endl;
cin >> continueGame;
if (continueGame == 0)
{
mainGame();
}
}
};
void mainGame()
{
gamer gamer;
while(gamer.gHealth >= 0 || gamer.gHealth <= 500)
{
cout << " aaaaaa" << endl;
gamer.gHealth -= 50;
cout << gamer.gHealth << endl ;
}
}
答案 0 :(得分:3)
您已声明了mainGame
函数作为您的gamer
类的成员,但从未真正定义。您接近了,但是忘记了在定义中声明它是该类的成员。以下应该可以工作:
void gamer::mainGame() // This is a member function of `gamer`, so declare it as such!
{
// gamer gamer; // We don't need this reference, as the member function will have...
while(gHealth >= 0 || gHealth <= 500) // ... an implied "this" object when called
{
cout << " aaaaaa" << endl;
gHealth -= 50; // Just using the member name on its own is enough to get it.
cout << gHealth << endl ;
}
}
在成员函数中,您不需要代码即可声明该类的对象!当调用该函数(由类的对象)时,该函数有效地接收到指向调用它的对象的指针。您可以使用this
关键字明确地访问该指针,但是通常不需要。只需在该函数中使用成员变量的名称,即可为调用该函数的对象引用该成员变量。