朋友见基类吗?

Wil*_*mKF 6 c++ inheritance private protected friend

给出示例代码:

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

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

Wil*_*mKF 7

结合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;
  }
};
Run Code Online (Sandbox Code Playgroud)