朋友看到基类吗? [英] Does a friend see base classes?

查看:61
本文介绍了朋友看到基类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出示例代码:

class Base {
public:
  bool pub;
protected:
  bool prot;
};

class Derived : private Base {
  friend class MyFriend;
};

class MyFriend {
  Derived _derived;

  void test() {
    // Does standard provide me access to _derived.pub and _derived.prot?
    cout << "Am I allowed access to this: " << _derived.pub
         << " and this: " << _derived.prot;
  }
};

成为朋友会让我获得所有访问权限,就像我是朋友所在类中的成员函数一样吗?换句话说,我是否可以成为自从成为朋友以来从私人继承的基类的受保护成员和公共成员?

Does being a friend give me all access I would get as if I was a member function within the class to which I am a friend? In other words, can I get at the protected and public members of the base class which is privately inherited from since I am a friend?

推荐答案

结合DavidRodríguez-dribeas和Luchian Grigore的答案:

Combining the answers of David Rodríguez - dribeas and Luchian Grigore:

是的,问题中的示例有效,但是,正如David指出的那样,不能直接通过基类访问受保护的成员.通过Derived访问时,您只能访问受保护的成员,通过Base访问时,您不能访问相同的成员.

Yes, the example in the question works, however, as David points out, the protected members are not accessible directly through the base class. You only get access to the protected members when accessed through Derived, you do not have access to the same members when accessed through Base.

换句话说,base的受保护成员被视为它们的派生成员,因此朋友可以看到它们,但是,如果您强制转换为基类,则没有朋友关系,因此受保护的成员不再可用.

In other words, the protected members of base are treated as if they were private members of derived and thus friends can see them, but, if you cast to the base class, there is no friend relationship, and thus the protected members are no longer accessible.

以下是一个说明差异的示例:

Here is an example that clarifies the difference:

class MyFriend {
  Derived _derived;

  void test() {
    bool thisWorks = _derived.pub;
    bool thisAlsoWorks = _derived.prot;

    Base &castToBase = _derived;

    bool onlyPublicAccessNow = castToBase.pub;
    // Compiler error on next expression only.
    // test.cpp:13: error: `bool Base::prot' is protected
    bool noAccessToProtected = castToBase.prot;
  }
};

这篇关于朋友看到基类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆