Friend access to protected nested class

前端 未结 2 1340
情书的邮戳
情书的邮戳 2021-01-11 15:08

I have the following C++ code:

class A {
 protected:
  struct Nested {
    int x;
  };
};

class B: public A {
  friend class C;
};

class C {
  void m1() {
         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-11 15:34

    In C++ friends are not-transitive. Friends of your friends are not necessarily my friends.

    By making Nested protected in A, you indicate that all subclasses may use this element, but nobody else is allowed to use it. You could consider this is a kind of friend. A makes all subclasses friend regarding access to the Nested struct.

    Now B makes C a friend, but this does not mean that C is also a friend of A. So C should have no access to Nested.

    BUT: the behavior is changed from C++03. In C++03, a nested class is a full member of the enclosing class and so has full access rights. Friendship is still NOT transitive, but now member access is.

    You may want to look at http://www.rhinocerus.net/forum/language-c-moderated/578874-friend-transitive-nested-classes.html, which explains a similar problem.

提交回复
热议问题