加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 朋友是否看到基类?

发布时间:2020-12-16 03:21:30 所属栏目:百科 来源:网络整理
导读:给出示例代码: 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
给出示例代码:
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;
  }
};

做朋友会给我所有的访问权限,我会得到好像我是班级中的一员,我是他的朋友吗?换句话说,由于我是朋友,我可以获得私人继承的基类的受保护和公共成员吗?

解决方法

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

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

换句话说,base的受保护成员被视为派生的私有成员,因此朋友可以看到它们,但是,如果你投射到基类,没有朋友关系,因此受保护的成员不再无障碍.

这是一个澄清差异的例子:

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;
  }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读