c++ - 嵌套类是否获得外部类的友元关系?

标签 c++ 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)的好友。因此,内部/嵌套类具有访问权限。

直接来自标准:

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/

相关文章:

c++ - 无故对 glEnd 进行无效操作?

c++ - 使用 QStyledItemDelegate 调整 QStandardItem 的选择行为

c++ - 重载运算符 << - 必须是二元运算符

c++ - 在模板类中定义友元函数

c++ - 如何使专门的功能模板成为某个类的 friend ?

C++ - 如何解决函数重载歧义

c++ - 在 C++ 中创建一个以 6 为基数的大型数组?

c++ - 重载运算符作为友元

c++ - 重载运算符*以获取对另一个类实例的引用

C++ - 必须在头文件中定义友元函数吗?