static變量在Main函數之前執行

一、例1

c/c++語言中,在執行main的入口函數之前,是會首先執行一段代碼。

而對於全局變量和static的初始化就是 在main函數之前執行的,例子如下:

  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. }  



執行結果爲:

  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

  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. }  

執行結果爲:

  1. <span style="color:#ff0000;">point ctor</span>  
  2. main() start  
  3. x=0, y=0, z=0  
  4. main() finish  
  5. point dtor  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章