【转】C++内部类

  1. #include <iostream.h> 
  2.  
  3. class Outer 
  4.       public: Outer() 
  5.       { 
  6.             cout<<"Invoke Outer Constructor"<<endl ; 
  7.       }  
  8.    
  9.       class Inner 
  10.       { 
  11.             public: Inner() 
  12.             { 
  13.                   cout<<"Invoke Inner Constructor"<<endl ; 
  14.             } 
  15.        }; 
  16.  
  17.        private: Inner inner ; //内部类的实例 
  18. }; 
  19.   
  20. int main(int argc, char* argv[]) 
  21.   
  22.        Outer outer ; 
  23.   
  24.        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.  
  4. #include "stdafx.h" 
  5. #include <iostream.h> 
  6.  
  7.  
  8. class Outer 
  9.     public: Outer() 
  10.     { 
  11.         cout<<"Invoke Outer Constructor"<<endl ; 
  12.     } 
  13.  
  14.     class Inner 
  15.     { 
  16.         public: Inner() 
  17.         { 
  18.             cout<<"Invoke Inner Constructor"<<endl ; 
  19.         } 
  20.     }; 
  21.  
  22. }; 
  23.  
  24. int main(int argc, char* argv[]) 
  25.         Outer out ; 
  26.  
  27.     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运行结果

总结:

这说明当在外部类中定义一个内部类,但是却没有这个内部类的类实例作为外部类的成员变量时,编译器只会调用外部类的构造方法,而不会调用内部类的构造器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值