【轉】C++內部類
阿新 • • 發佈:2018-12-26
- #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去掉。執行結果又會怎樣呢?請見下面的程式碼及執行結果。
- // 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;
- }
程式執行結果:
總結:
這說明當在外部類中定義一個內部類,但是卻沒有這個內部類的類例項作為外部類的成員變數時,編譯器只會呼叫外部類的構造方法,而不會呼叫內部類的構造器。