#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)的好友。因此,内部/嵌套类具有访问权限。
直接来自标准:
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
};
};
关于c++ - 嵌套类是否获得外部类的友元关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45488044/