【问题标题】:Does a friend see base classes?有朋友看到基类吗?
【发布时间】:2012-04-10 08:18:15
【问题描述】:

给出示例代码:

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

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

【问题讨论】:

  • 看到您费尽心思编写示例代码,您是否尝试过编译它?这种答案很快就会在警告/缺乏中浮出水面。
  • @peachykeen:编译器接受的内容和标准所说的内容通常是不同的。此外,理论上,示例代码可能没有捕捉到细微之处。
  • @AdrianMcCarthy 这是真的。然而,当使用非标准特性时,许多编译器会发出警告,如果它违反标准和编译器的实现,你会得到一个简短而甜蜜的答案。虽然不是万无一失,但尝试一下也无妨。

标签: c++ inheritance private friend protected


【解决方案1】:

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

是的,问题中的示例有效,但是,正如大卫指出的那样,受保护的成员不能直接通过基类访问。通过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;
  }
};

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

      【解决方案3】:

      是的,因为Base 的成员也是Derived 的成员(因为他们不是Base 中的private)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-21
        • 2011-04-17
        • 2012-12-04
        • 1970-01-01
        • 2021-03-21
        • 2011-08-10
        相关资源
        最近更新 更多