朋友看到基类了吗

Does a friend see base classes?

本文关键字:基类 朋友      更新时间:2023-10-16

给定示例代码:

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

作为朋友是否能让我获得所有访问权限,就好像我是朋友所在类中的成员函数一样?换言之,我可以攻击基类的受保护和公共成员吗?因为我是朋友,所以基类是私人继承的?

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

是的,问题中的例子是有效的,但是,正如David所指出的,受保护的成员不能直接通过基类访问。通过Derived访问时,您只能访问受保护的成员,通过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;
  }
};

friend声明将使MyFriend有权访问继承关系(对于世界其他地方来说是private),但不会授予它对受保护的基成员的访问权限,只授予它对公共接口的访问权限。

void MyFriend::test() {
   Derived d;
   Base & b = d;          // Allowed, MyFriend has access to the relationship
   b.prot = false;        // Not allowed, it does not have access to the base
}
是的,因为Base的成员也是Derived的成员(因为它们不是Base中的private)。