Reputation: 27
I'm trying to make a small mini game where a class Hero
interacts with class Enemy
variables using friend
but the code is unable to compile and gives me the forward declaration error
#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;
}
I was told that static
functions and variables are able to prevent this error as they are global
as it pre-compiles the build
Upvotes: 1
Views: 63
Reputation: 223767
There are two main issues here.
First, when defining Hero::attackEnemy
, the static
qualifier is invalid here. The member is already declared as static
in the class definition, so no need to apply it here as well.
Second, at the time Hero::attachEnemy
is defined, the Enemy
class still has not been defined. You need to move the definition of Hero::attachEnemy
after the definition of class Enemy
.
class Enemy;
class Hero {
...
};
class Enemy {
...
};
void Hero::attackEnemy(Enemy *e1, Hero *h1)
{
e1->hp -= h1->power;
}
Also, this is not a valid function / method call:
h1->attackEnemy(Enemy *e1, Hero *h1);
You want:
h1->attackEnemy(e1, h1);
Upvotes: 3