Can Inner Classes Access Private Variables?
Consider the following C code:
class Outer { class Inner { public: Inner() {} void func(); }; private: static const char* const MYCONST; int var; }; void Outer::Inner::func() { var = 1; } const char* const Outer::MYCONST = "myconst";
Upon compilation, this code generates an error: "class Outer::Inner' has no member named var'". This prompts the question: can inner classes access private variables of the outer class?
Answer:
Yes, inner classes have access to the private variables of the enclosing class. This is because inner classes are friends of their enclosing classes.
However, unlike Java, there is no direct relationship between an inner class object and the encompassing class object. To establish this connection, you must establish it manually.
Solution:
The following modified code connects the inner and outer class objects by passing a reference to the outer class to the inner class constructor:
#include <string> #include <iostream> class Outer { class Inner { public: Inner(Outer& x): parent(x) {} void func() { std::string a = "myconst1"; std::cout << parent.var << std::endl; if (a == MYCONST) { std::cout << "string same" << std::endl; } else { std::cout << "string not same" << std::endl; } } private: Outer& parent; }; public: Outer() :i(*this) ,var(4) {} Outer(Outer& other) :i(other) ,var(22) {} void func() { i.func(); } private: static const char* const MYCONST; Inner i; int var; }; const char* const Outer::MYCONST = "myconst"; int main() { Outer o1; Outer o2(o1); o1.func(); o2.func(); }
This code eliminates the compilation error and allows the inner class to access the private variables of the outer class.
The above is the detailed content of Can Inner Classes Access Outer Class Private Variables in C ?. For more information, please follow other related articles on the PHP Chinese website!