class 层级的私有继承,为什么整个层级都需要 friend

Private inheritance along class hierarchy, why friend is needed all along the hierarchy

考虑以下代码:

#include <iostream>

class A{
    friend class C;
    int a{42};
};

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

class C: private B {
public:
    void print() {std::cout << a << '\n';}
};

int main() {
    C c;
    c.print();
}

根据this answer,成员变量A::a在所有类中都是"present",但其可见性不同,即在B中不可见或 C 除非我们让 BC 成为 A 的朋友。我的问题是为什么我需要让 C 成为 AB 的朋友?我本来认为 A 中的朋友声明就足够了。如果我从 AB 中删除 friend class C; 声明,代码将无法编译。

My question is why do I need to make C a friend of both A and B?

如果没有 B 声明 C 有朋友,C 就不会 看到 B 继承 A.即使 Csee A::a,也不会 see B::a.

确实:

  • C 继承了 B,因此 B 中的任何 public 都可以从 C 访问。
  • 但是 BA 私下 继承。 C 成为 B 的朋友使得 C 看到 这种继承。
  • A::a的访问权限是私有的,因此即使CA视为其祖先,也需要成为朋友从 A 参见 A::a.