A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.
For example, program 1 compiles without any error and program 2 fails in compilation.
Program1
1 //Program 1
2
3 #include<iostream>
4
5 using namespace std;
6
7 /* start of Enclosing class declaration */
8 class Enclosing
9 {
10 public: //if remove the keyword, may be wrong in some compiler
11 int x;
12
13 /* start of Nested class declaration */
14 class Nested
15 {
16 int y;
17 void NestedFun(Enclosing *e)
18 {
19 cout << e->x; // works fine: nested class can access private members of Enclosing class
20 }
21 }; // declaration Nested class ends here
22 }; // declaration Enclosing class ends here
23
24 int main()
25 {
26
27 }
Program 2
1 #include<iostream>
2
3 using namespace std;
4
5 /* start of Enclosing class declaration */
6 class Enclosing
7 {
8
9 int x;
10
11 /* start of Nested class declaration */
12 class Nested
13 {
14 int y;
15 }; // declaration Nested class ends here
16
17 void EnclosingFun(Nested *n)
18 {
19 cout << n->y; // Compiler Error: y is private in Nested
20 }
21 }; // declaration Enclosing class ends here
22
23 int main()
24 {
25
26 }
References: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-27 14:40:49