为什么仅在使用 public 继承时派生 类 的友元函数 "available"?
Why are friend functions "available" for derived classes only when using public inheritance?
当派生 class 通过 public 访问从基础 class 继承时,问题与 中的问题相同。但是,如果它通过受保护或私有访问继承,则会出现可见性错误。
当它通过 public 访问继承时,A 的私有成员的可访问性与通过私有访问继承相同。它们有什么区别?
class A {
private:
int a;
friend void f();
};
class B : private A {
};
void f() {
B obj;
int x = obj.a;
}
int main() {
f();
return 0;
}
正如上面链接的答案中已经指出的那样,友谊不会被继承。因此,A
的朋友不是 B
的朋友。 B
通过 private
访问继承自 A
意味着 A
的所有成员都可以作为 B
[class.access.base]/1. Since f
is not a friend of B
, it cannot access private members of B
[class.access]/1.1. Since f
is not a friend of B
, the base class A
of B
is also not accessible from f
[class.access.base]/4. Since the base class A
of B
is not accessible from f
, there's also no way you could get to the A
subobject of a B
(of which you could access the members) in f
[class.access.base]/5…[=32 的私有成员访问=]
当派生 class 通过 public 访问从基础 class 继承时,问题与
当它通过 public 访问继承时,A 的私有成员的可访问性与通过私有访问继承相同。它们有什么区别?
class A {
private:
int a;
friend void f();
};
class B : private A {
};
void f() {
B obj;
int x = obj.a;
}
int main() {
f();
return 0;
}
正如上面链接的答案中已经指出的那样,友谊不会被继承。因此,A
的朋友不是 B
的朋友。 B
通过 private
访问继承自 A
意味着 A
的所有成员都可以作为 B
[class.access.base]/1. Since f
is not a friend of B
, it cannot access private members of B
[class.access]/1.1. Since f
is not a friend of B
, the base class A
of B
is also not accessible from f
[class.access.base]/4. Since the base class A
of B
is not accessible from f
, there's also no way you could get to the A
subobject of a B
(of which you could access the members) in f
[class.access.base]/5…[=32 的私有成员访问=]