http://blog.youkuaiyun.com/rabbit729/article/details/3334272
http://blog.youkuaiyun.com/hihui/article/details/4822412
在一个类的内部定义另一个类,我们称之为嵌套类(nested class),或者嵌套类型。之所以引入这样一个嵌套类,往往是因为外围类需要使用嵌套类对象作为底层实现,并且该嵌套类只用于外围类的实现,且同时可以对用户隐藏该底层实现。
- #ifndef NESTCLASS_H_
- #define NESTCLASS_H_
- class A
- {
- public:
- A();
- ~A();
- void operate();
- private:
- class B;
- B* m_b;
- };
- #endif
- #include "nestclass.h"
- #include <iostream>
- using namespace std;
- class A::B
- {
- public:
- B(){}
- ~B(){}
- void operate()
- {
- cout<<"B operate!"<<endl;
- }
- };
- A::A()
- {
- }
- A::~A()
- {
- }
- void A::operate()
- {
- m_b = new B;
- cout<<"A operate!"<<endl;
- m_b->operate();
- }
- #include "nestclass.h"
- void main()
- {
- A a;
- a.operate();
- }
内部类其实就是一种在类声明里面定义的一种局部数据类型。
---- 内部类的声明有public和private之分
如果声明为public,那么外面也可以用它来定义变量,比如Outer::Inner var
如果声明为private,那么外面不能用来定义变量,那么Outer::Inner var将会导致编译错误。
---- 内部类声明完之后就可以用来定义变量
这就和别的数据类型定义变量一样了,访问规则也一样。无他
---- 内部类和外部类的互相访问
不能访问, 完全依赖于成员变量的定义属性。
---- For example
1 #include <iostream>
2 using namespace std;
3
4 class A
5 {
6 public:
7 class B1
8 {
9 public: int a;
10 private: int b;
11 public: void foo(A &p) {
12 cout << p.i1 << endl; // OK, because i1 is public in class A
13 cout << p.i2 << endl; // Fail, because i2 is private in class A
14 }
15 };
16
17 private:
18 class B2
19 {
20 public: int a;
21 private: int b;
22 public: void foo(A &p) {
23 cout << p.i1 << endl; // OK, because i1 is public in class A
24 cout << p.i2 << endl; // Fail, because i2 is private in class A
25 }
26 };
27
28 public:
29 B1 b11;
30 B2 b12;
31 int i1;
32 private:
33 B1 b21;
34 B2 b22;
35 int i2;
36 public:
37 void f(B1& p) {
38 cout << p.a << endl; // OK, because a is public in class B1
39 cout << p.b << endl; // Fail, because b is private in class B1
40 }
41 void f(B2& p) {
42 cout << p.a << endl; // OK, because a is public in class B2
43 cout << p.b << endl; // Fail, because b is private in class B2
44 }
45 };
46
47 int main(int argc, char *argv[])
48 {
49 A a ;
50 A::B1 ab1; // OK, because B1 is declared as public inner class.
51 A::B2 ab2; // Fail, because B2 is declared as private inner class
52 return 0;
53 }