Nested class member access on C++11

给你一囗甜甜゛ 提交于 2019-11-29 08:55:37

Here is the change within C++11 from cppreference;

Declarations in a nested class can use only type names, static members, and enumerators from the enclosing class (until C++11)

Declarations in a nested class can use any members of the enclosing class, following the usual usage rules for the non-static members. (since C++11)

int x,y; // globals
class enclose { // enclosing class
    int x; // note: private members
    static int s;
 public:
    struct inner { // nested class
        void f(int i) {
            x = i; // Error: can't write to non-static enclose::x without instance
            int a = sizeof x; // Error until C++11,
                              // OK in C++11: operand of sizeof is unevaluated,
                              // this use of the non-static enclose::x is allowed.
            s = i;   // OK: can assign to the static enclose::s
            ::x = i; // OK: can assign to global x
            y = i;   // OK: can assign to global y
        }
        void g(enclose* p, int i) {
            p->x = i; // OK: assign to enclose::x
        }
    };
};

In brief, within C++11, nested class can refer to types and static members of its enclosing class. In addition, it can refer to non-static members only when object of the enclosing class is given to the nested class. A nested class has access to members of its enclosing class including private members.

To close this question I'll take this as an answer:

"No, it's not treated as a member of the class, it's just scoped inside of it like anything else. You'll need an instance of Enclosing to access it's members."

  • this and several other comments addresses the problem in my code. Basically this is something that remains true for C++11.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!