[英]Unable to access private variables inside of static functions
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 我正在尝试制作一个小型迷你游戏,其中一个
class Hero
使用friend
与class Enemy
变量交互,但代码无法编译并给我前向声明错误
#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 有人告诉我,
static
函数和变量能够防止这个错误,因为它们是global
因为它预先编译了构建
There are two main issues here. 这里有两个主要问题。
First, when defining Hero::attackEnemy
, the static
qualifier is invalid here. 首先,在定义
Hero::attackEnemy
, static
限定符在此处无效。 The member is already declared as static
in the class definition, so no need to apply it here as well. 该成员已在类定义中声明为
static
,因此不需要在此处应用它。
Second, at the time Hero::attachEnemy
is defined, the Enemy
class still has not been defined. 其次,在定义
Hero::attachEnemy
, Enemy
类仍未定义。 You need to move the definition of Hero::attachEnemy
after the definition of class Enemy
. 在
class Enemy
定义之后 ,你需要移动Hero::attachEnemy
的定义。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.