1. 程式人生 > >【轉】C++內部類

【轉】C++內部類

  1. #include <iostream.h>
  2. class Outer 
  3.       public: Outer() 
  4.       { 
  5.             cout<<"Invoke Outer Constructor"<<endl ; 
  6.       }  
  7.       class Inner 
  8.       { 
  9.             public: Inner() 
  10.             { 
  11.                   cout<<"Invoke Inner Constructor"<<endl ; 
  12.             } 
  13.        }; 
  14.        private: Inner inner ; //內部類的例項
  15. }; 
  16. int main(int argc, char* argv[]) 
  17.        Outer outer ; 
  18.        return 0; 
#include <iostream.h> class Outer { public: Outer() { cout<<"Invoke Outer Constructor"<<endl ; } class Inner { public: Inner() { cout<<"Invoke Inner Constructor"<<endl ; } }; private: Inner inner ; //內部類的例項 }; int main(int argc, char* argv[]) { Outer outer ; return 0; }

程式執行結果:

執行結果

總結:

這說明當外部類中的一個成員變數是內部類的例項時,編譯器會首先對內部類例項進行構造,呼叫其構造方法。其次再對外部類的構造方法進行呼叫。

程式2:

     現在,如果我們把外部類中的成員變數——內部類例項inner去掉。執行結果又會怎樣呢?請見下面的程式碼及執行結果。

  1. // Test090430.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <iostream.h>
  5. class Outer 
  6.     public: Outer() 
  7.     { 
  8.         cout<<"Invoke Outer Constructor"<<endl ; 
  9.     } 
  10.     class Inner 
  11.     { 
  12.         public: Inner() 
  13.         { 
  14.             cout<<"Invoke Inner Constructor"<<endl ; 
  15.         } 
  16.     }; 
  17. }; 
  18. int main(int argc, char* argv[]) 
  19.         Outer out ; 
  20.     return 0; 
// Test090430.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream.h> class Outer { public: Outer() { cout<<"Invoke Outer Constructor"<<endl ; } class Inner { public: Inner() { cout<<"Invoke Inner Constructor"<<endl ; } }; }; int main(int argc, char* argv[]) { Outer out ; return 0; }

程式執行結果:

程式2執行結果

總結:

這說明當在外部類中定義一個內部類,但是卻沒有這個內部類的類例項作為外部類的成員變數時,編譯器只會呼叫外部類的構造方法,而不會呼叫內部類的構造器。