我正在尝试制作一个小型迷你游戏,其中class Hero
使用class Enemy
与friend
变量进行交互,但是代码无法编译,并给了我前向声明错误>
#include <iostream>
class Enemy;
class Hero
{
friend class Enemy;
private:
static int hp, power;
public:
Hero *h1;
Hero ()
{
hp = 50;
power = 10;
}
static void attackEnemy (Enemy *e1, Hero *h1);
};
static void Hero::attackEnemy(Enemy *e1, Hero *h1)
{
e1->hp -= h1->power;
}
class Enemy
{
friend class Hero;
private:
static int hp, power;
public:
Enemy ()
{
hp = 15;
power = 10;
}
void attackHero ();
};
int main ()
{
Enemy *e1 = new Enemy ();
Hero *h1 = new Hero ();
h1->attackEnemy(Enemy *e1, Hero *h1);
return 0;
}
有人告诉我static
函数和变量可以防止此错误,因为它们global
是在预编译版本时
答案 0 :(得分:3)
这里有两个主要问题。
首先,在定义Hero::attackEnemy
时,static
限定词在这里无效。该成员已在类定义中声明为static
,因此也无需在此处应用它。
第二,在定义Hero::attachEnemy
时,Enemy
类仍未定义。您需要将Hero::attachEnemy
的定义移至class Enemy
的后方。
class Enemy;
class Hero {
...
};
class Enemy {
...
};
void Hero::attackEnemy(Enemy *e1, Hero *h1)
{
e1->hp -= h1->power;
}
此外,这不是有效的函数/方法调用:
h1->attackEnemy(Enemy *e1, Hero *h1);
您要
h1->attackEnemy(e1, h1);