static变量在Main函数之前执行

一、例1

c/c++语言中,在执行main的入口函数之前,是会首先执行一段代码。

而对于全局变量和static的初始化就是 在main函数之前执行的,例子如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <iostrem.h>  
  2.   
  3. #include  <stdio.h>  
  4.   
  5. class static_name  
  6.   
  7. {  
  8.   
  9. public:  
  10.   
  11.     static_name(){};  
  12.   
  13.     static int  static_print();  
  14.   
  15. private:  
  16.   
  17.     static  int  i_static_value;  
  18.   
  19. };  
  20.   
  21. int static_name:static_print()  
  22.   
  23. {  
  24.   
  25.     printf("This is static!!\n");  
  26.   
  27.     return 1;  
  28.   
  29. }  
  30.   
  31. int static_name::i_static_value=static_name::static_print();  
  32.   
  33. int main()  
  34.   
  35. {  
  36.   
  37.     printf("This is main_function()!!\n");  
  38.   
  39.     return 0;  
  40.   
  41. }  



执行结果为:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. This is static!!  
  2.   
  3. This is main_function()!!  


这就说明:

1.类中static变量是可以不在构造函数中初始化的,可以在类外面单独初始化。

2.static变量初始化执行,是在main入口函数之前就完成的操作。


【转自:http://blog.csdn.net/zhghost/article/details/8693494】


再看例2:


二、例2

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <boost/serialization/singleton.hpp>  
  2. using namespace std;  
  3. using boost::serialization::singleton;  
  4.   
  5. class Point  
  6. {  
  7. public:  
  8.     explicit Point(int a=0, int b=0, int c=0):x(a),y(b),z(c)  
  9.     {  
  10.         cout<<"point ctor"<<endl;  
  11.     }  
  12.     ~Point()  
  13.     {  
  14.         cout<<"point dtor"<<endl;  
  15.     }  
  16.     void Print()const  
  17.     {  
  18.         cout<<"x="<<x<<", y="<<y<<", z="<<z<<endl;  
  19.     }  
  20. private:  
  21.     int x, y, z;  
  22. };  
  23.   
  24. int main ( )  
  25. {  
  26.     cout<<"main() start"<<endl;  
  27.     typedef singleton<Point> origin;  
  28.   
  29.     origin::get_const_instance().Print();  
  30.       
  31.     cout<<"main() finish"<<endl;  
  32.   
  33.     return 0;  
  34. }  

执行结果为:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="color:#ff0000;">point ctor</span>  
  2. main() start  
  3. x=0, y=0, z=0  
  4. main() finish  
  5. point dtor  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值