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
除非我们让 B
或 C
成为 A
的朋友。我的问题是为什么我需要让 C
成为 A
和 B
的朋友?我本来认为 A
中的朋友声明就足够了。如果我从 A
或 B
中删除 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
.即使 C
会 see A::a
,也不会 see B::a
.
确实:
C
继承了 B
,因此 B
中的任何 public 都可以从 C
访问。
- 但是
B
从 A
中 私下 继承。 C
成为 B
的朋友使得 C
看到 这种继承。
A::a
的访问权限是私有的,因此即使C
将A
视为其祖先,也需要成为朋友从 A
到 参见 A::a
.
考虑以下代码:
#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
除非我们让 B
或 C
成为 A
的朋友。我的问题是为什么我需要让 C
成为 A
和 B
的朋友?我本来认为 A
中的朋友声明就足够了。如果我从 A
或 B
中删除 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
.即使 C
会 see A::a
,也不会 see B::a
.
确实:
C
继承了B
,因此B
中的任何 public 都可以从C
访问。- 但是
B
从A
中 私下 继承。C
成为B
的朋友使得C
看到 这种继承。 A::a
的访问权限是私有的,因此即使C
将A
视为其祖先,也需要成为朋友从A
到 参见A::a
.