一、例1
c/c++语言中,在执行main的入口函数之前,是会首先执行一段代码。
而对于全局变量和static的初始化就是 在main函数之前执行的,例子如下:
- #include <iostrem.h>
- #include <stdio.h>
- class static_name
- {
- public:
- static_name(){};
- static int static_print();
- private:
- static int i_static_value;
- };
- int static_name:static_print()
- {
- printf("This is static!!\n");
- return 1;
- }
- int static_name::i_static_value=static_name::static_print();
- int main()
- {
- printf("This is main_function()!!\n");
- return 0;
- }
执行结果为:
- This is static!!
- This is main_function()!!
这就说明:
1.类中static变量是可以不在构造函数中初始化的,可以在类外面单独初始化。
2.static变量初始化执行,是在main入口函数之前就完成的操作。
【转自:http://blog.csdn.net/zhghost/article/details/8693494】
再看例2:
二、例2
- #include <boost/serialization/singleton.hpp>
- using namespace std;
- using boost::serialization::singleton;
- class Point
- {
- public:
- explicit Point(int a=0, int b=0, int c=0):x(a),y(b),z(c)
- {
- cout<<"point ctor"<<endl;
- }
- ~Point()
- {
- cout<<"point dtor"<<endl;
- }
- void Print()const
- {
- cout<<"x="<<x<<", y="<<y<<", z="<<z<<endl;
- }
- private:
- int x, y, z;
- };
- int main ( )
- {
- cout<<"main() start"<<endl;
- typedef singleton<Point> origin;
- origin::get_const_instance().Print();
- cout<<"main() finish"<<endl;
- return 0;
- }
执行结果为:
- <span style="color:#ff0000;">point ctor</span>
- main() start
- x=0, y=0, z=0
- main() finish
- point dtor