Nested class access to enclosing class members

泄露秘密 提交于 2021-02-20 04:12:54

问题


From C++ Primer 5th edition By Stanley Lippman et al(19.5):

A nested class can have the same kinds of members as a nonnested class. Just like any other class, a nested class controls access to its own members using access specifiers. The enclosing class has no special access to the members of a nested class, and the nested class has no special access to members of its enclosing class.

Is there any truth to the bolded part? I could find no mention of the nested class being restricted access to enclosing class members in the standard (9.7 N3337) and the following code compiles fine (g++ 5.2.0)

#include <iostream>

struct A{
private:
    typedef int woah;
public:
    struct B{
        woah x = 5;
        void test() { A f; std::cout << f.x;}
    };
private:
    int x = 5;
};

int main(){
    A::B j;
    j.test();
}

There being two parts here:

  1. B accesses the private type alias woah to define its own member.
  2. The member function test of B accesses the private x member of an A object.

Of course the opposite seems to be true as the quote says: A cannot access private members of B (not that this example shows that). So is this a blunder on my book's part or am I misunderstanding what it is saying?


回答1:


It was decided that the lack of access of nested classes was a mistake in the Standard, and subsequently rectified. Now nested classes enjoy the same levels of access as all members, namely total access.



来源:https://stackoverflow.com/questions/34976995/nested-class-access-to-enclosing-class-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!