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

时间:2019-03-06 03:54:36

标签: c++ class oop static friend

我正在尝试制作一个小型迷你游戏,其中class Hero使用class Enemyfriend变量进行交互,但是代码无法编译,并给了我前向声明错误

#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是在预编译版本时

1 个答案:

答案 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);