简体   繁体   English

无法访问静态函数内的私有变量

[英]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使用friendclass 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::attackEnemystatic限定符在此处无效。 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::attachEnemyEnemy类仍未定义。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM