C++中全局对象的初始化顺序(三)

2013-09-26 19:50:47 · 作者: · 浏览: 220

 

  #endif // INDEPENDENT_H

  //*************Independent.cpp********************

  #include "Independent.h"

  #include <iostream>

  using namespace std;

  Independent::Independent()

  {

  cout《"Independent::Independent(), o1"《endl;

  }

  Independent::~Independent()

  {

  cout《"Independent::~Independent()。"《endl;

  }

  const Independent *o1;

  //*************dependent.h********************

  #ifndef DEPENDENT_H

  #define DEPENDENT_H

  #include "Independent.h"

  class Dependent

  {

  public:

  virtual ~Dependent();

  Dependent(Independent* a);

  protected:

  private:

  Dependent();

  };

  #endif // DEPENDENT_H

  //*************Dependent.cpp********************

  #include "Dependent.h"

  #include <iostream>

  #include "Independent.h"

  using namespace std;

  extern Independent *o1;

  Dependent::Dependent()

  {

  cout《"Dependent::Dependent(), o2"《endl;

  }

  Dependent::Dependent(Independent* a)

  {

  if(a == NULL)

  a = new Independent();

  cout《"Dependent::Dependent(Independent* a) o2"《endl;

  }

  Dependent::~Dependent()

  {

  cout《"Dependent::~Dependent()。"《endl;

  }

  Dependent o2(o1);

  //*************main.cpp********************

  #include <iostream>

  using namespace std;

  int main()

  {

  return 0;

  }

  下面是程序运行的结果:

 

  很明显,o2依赖于o1, 而o1也在o2之前被构造出来了。

  总结:

  1.我们要尽可能少用全局变量

  2.可以将一个对象的构造函数作为另一个对象构造函数的参数来保证他们的构造顺序