友元函数不能访问私有成员变量

Friend function cannot access private member variable

我有两个 class,PlayerCharacterAbilityAbility class 有一个纯虚函数,我将其声明为 friendPlayerCharacter。但是,我似乎无法访问 friend 声明函数中的私有成员。是我忽略了什么吗?

我试图将子函数而不是虚拟函数声明为友元函数,但没有效果。

player_chracter.h :

#include "ability.h"

class PlayerCharacter : public Character {
private:
    // Friend function
    friend bool Ability::ExecuteAbility(PlayerCharacter& in_player);

    // This doesn't work either
    //friend bool Dash::ExecuteAbility(PlayerCharacter& in_player);

    // Private variable
    float top_speed_;
}

ability.h :

//Forward declaration
class PlayerCharacter;

class Ability {
public:
    Ability();
    ~Ability();
    virtual bool ExecuteAbility(PlayerCharacter& in_player) = 0;
};
//---------------------------------------------------------
class Dash : public Ability {
public:
    Dash();
    ~Dash();
    bool ExecuteAbility(PlayerCharacter& in_player);
};

ability.cpp :

#include "ability.h"
#include "player_character.h"   //Follow through on forward declaraction

bool Dash::ExecuteAbility(PlayerCharacter& in_player) {
    float example = in_player.top_speed_;
}

在上面的代码中,为什么我不能访问 top_speed_ 并将其放在 float example 变量中?

根据[class.friend]/10,友谊不会被继承。 派生 class 不会自动成为 class 的好友,仅仅因为其父 class 是 class.

的好友

以下也不起作用的原因可能是因为在定义函数ExecuteAbility之前未定义Dash

friend bool Dash::ExecuteAbility(PlayerCharacter& in_player);

但是,使用 正确的定义顺序 它将起作用。参见 DEMO

来自cppreference

Friendship is not transitive (a friend of your friend is not your friend)

Friendship is not inherited (your friend's children are not your friends)

即使 Dash::ExecuteAbility 从其基础 class 覆盖了 friend 函数,它也不会从中受益。您将不得不重新考虑您的设计。