1. 程式人生 > >c++內部類和外部類(java)

c++內部類和外部類(java)

(1)簡介:

內部類其實就是一種在類聲明裡面定義的一種區域性資料型別。(非常類似於struct Node宣告的),這和java的還有存在區別的。

---- 內部類的宣告有public和private之分

如果宣告為public,那麼外面也可以用它來定義變數,比如Outer::Inner var

如果宣告為private,那麼外面不能用來定義變數,那麼Outer::Inner var將會導致編譯錯誤。

(2)---- 內部類宣告完之後就可以用來定義變數

這就和別的資料型別定義變數一樣了,訪問規則也一樣。無他

---- 內部類和外部類的互相訪問

不能訪問, 完全依賴於成員變數的定義屬性。

(3)程式碼實現(請看下面的註釋,這裡不做過多解釋了)


#include <iostream>
using namespace std;
class A
{
    public:
		class B1
		{
             public: int a;
             private: int b;
             public: void foo(A &p) 
			 { 
				cout << p.i1 << endl;      // OK, because i1 is public in class A
            	cout << p.i2 << endl;      // Fail, because i2 is private in class A
            }
        };  
	private:
        class B2
        {
            public: int a;
            private: int b;
            public: void foo(A &p) 
			{
                cout << p.i1 << endl;      // OK, because i1 is public in class A
				cout << p.i2 << endl;      // Fail, because i2 is private in class A
			}
		};
  
    public:
		B1 b11;
		B2 b12;
		int i1;
	private:
		B1 b21;
		B2 b22;
		int i2;
	public: 
		void f(B1& p) 
		{ 
			cout << p.a << endl;      // OK, because a is public in class B1
            cout << p.b << endl;      // Fail, because b is private in class B1
        }
        void f(B2& p) 
		{ 
            cout << p.a << endl;      // OK, because a is public in class B2
			cout << p.b << endl;      // Fail, because b is private in class B2
        }
};
int main(int argc, char *argv[])
{
	A a ;
	A::B1 ab1;                              // OK, because B1 is declared as public inner class.
	A::B2 ab2;                              // Fail, because B2 is declared as private inner class
    return 0;
}