C++內部類
內部類其實就是一種在類聲明裡面定義的一種區域性資料型別。
---- 內部類的宣告有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 }