嵌套的classes是否获得外部class的友情关系?
Do nested classes obtain friendship relations of outer class?
#include <iostream>
#include <string>
class A {
friend class B;
std::string m = "Hello";
};
struct B {
struct N {
void f(){
A a;
std::cout << a.m << std::endl;
};
};
};
int main() {
B::N().f();
}
是否允许N访问m?
编辑
好的,我 运行 它在 cpp.sh 中,显然它有效。是否有通用规则来理解如何获得友谊关系?
标准很明确,友谊不会被继承:
14.3/10: "Friendship is neither inherited nor transitive"
但是嵌套 class 是 不是 继承。它是一个成员。如果 class 是朋友,则其成员可以访问 class 的朋友。因此,inner/nested class 具有访问权限。
直接来自标准:
14.3/2 Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can
be accessed in the base-specifiers and member declarations of the
befriended class. Example:
class A {
class B { };
friend class X;
};
struct X : A::B { // OK: A::B accessible to friend
A::B mx; // OK: A::B accessible to member of friend
class Y {
A::B my; // OK: A::B accessible to nested member of friend
};
};
#include <iostream>
#include <string>
class A {
friend class B;
std::string m = "Hello";
};
struct B {
struct N {
void f(){
A a;
std::cout << a.m << std::endl;
};
};
};
int main() {
B::N().f();
}
是否允许N访问m?
编辑
好的,我 运行 它在 cpp.sh 中,显然它有效。是否有通用规则来理解如何获得友谊关系?
标准很明确,友谊不会被继承:
14.3/10: "Friendship is neither inherited nor transitive"
但是嵌套 class 是 不是 继承。它是一个成员。如果 class 是朋友,则其成员可以访问 class 的朋友。因此,inner/nested class 具有访问权限。
直接来自标准:
14.3/2 Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class. Example:
class A {
class B { };
friend class X;
};
struct X : A::B { // OK: A::B accessible to friend
A::B mx; // OK: A::B accessible to member of friend
class Y {
A::B my; // OK: A::B accessible to nested member of friend
};
};