c++ - 如果 Outer 类是我的 friend ,那么 Outer::Inner 类也是吗?

标签 c++ language-lawyer friend member-access

以下代码在 MSVC 上编译:

#include <iostream>

class Bob
{        
    int a;
    friend class Outer;
};
class Outer
{      
    class Inner
    {
        void f(Bob obj)
        {
            std::cout << obj.a; //OK
        }
    };
};

所以看起来如果 Outer 是 Bob 的 friend ,那么 Inner 也是自动的。我正在阅读标准的 Friends 章节,但找不到可以证实或反驳这一点的条款。

这是否合法,如果合法,章节是什么?

最佳答案

[class.access.nest]/1 指出

A nested class is a member and as such has the same access rights as any other member

所以我相信是的,这是标准行为。

假设 Outer 有一个成员函数 foo()。当然,该函数将有权访问 Bob 的成员。据我了解,我引用的部分暗示 Outer 中的任何嵌套类都将具有与 foo() 相同的访问权限,因此能够访问 Bob 的成员。

另外值得注意的是,该标准包含以下示例([class.friend]/2),请注意A::B的用法>Y:

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++ - 如果 Outer 类是我的 friend ,那么 Outer::Inner 类也是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42926317/

相关文章:

c++ - reinterpret_cast 指向 void(*&)() 的成员函数指针

c++ - 是一个函数指针 odr-如果它被调用

c++ - 派生类可以访问作为内部类的友元的父类的 protected 内部类的私有(private)方法吗?

c++ - 友元和继承有什么区别?

c++ - 寻求简单内存数据库*服务器*的建议(不需要持久性)

c++ - 使用Vector实现Stack的问题

c++ - 为什么仅仅因为有一个用户定义的析构函数,复制构造函数就不是微不足道的了?

c++ - 虚拟指针

c++ - C++11 PRNG 能否用于产生可重复的结果?

c++ - 一个类的另一个类的 friend 的功能