【问题标题】:Friend function cannot access private member variableFriend 函数无法访问私有成员变量
【发布时间】:2019-07-12 17:35:13
【问题描述】:

我有两个课程,PlayerCharacterAbilityAbility 类有一个纯虚函数,我将其声明为 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变量中?

【问题讨论】:

  • 能否在这两种情况下添加错误消息?

标签: c++ friend pure-virtual


【解决方案1】:

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

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

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

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

【讨论】:

  • 确实如此。感谢您的帮助。
【解决方案2】:

来自cppreference

友谊不是传递的(你朋友的朋友不是你的朋友)

友谊不是遗传的(你朋友的孩子不是你的朋友)

即使Dash::ExecuteAbility 覆盖其基类中的friend 函数,它也不会从中受益。你必须重新考虑你的设计。

【讨论】:

  • 嗨昆汀。你怎么解释// This doesn't work either //friend bool Dash::ExecuteAbility(PlayerCharacter& in_player);
  • @YSC 这个问题缺少错误的副本(我是不是回答得太早了?可能。)但我怀疑这只是 Dash 没有事先定义的情况。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
  • 2023-03-23
  • 2021-02-04
相关资源
最近更新 更多