萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> C++ 靜態成員變量 嵌套類分配回收內存

C++ 靜態成員變量 嵌套類分配回收內存

  嵌套類分配回收內存:

  #include <stdio.h>

  #include <assert.h>

  class CA

  {

  public:

  inline static CA *GetInstance(void)

  {

  assert(m_instance != NULL);

  return m_instance;

  }

  void Print(void)

  {

  puts("主類的Print函數運行看看");

  }

  class Garbage//用來分配內存的嵌套類

  {

  public:

  Garbage(int i, int j)

  {

  printf("Garbage分配內存開始:%d %dn", i, j);

  m_instance = new CA(123123, 234234234);

  }

  ~Garbage()

  {

  delete m_instance;

  puts("Garbage收拾殘局結束");

  }

  };

  static Garbage m_garbage;

  protected:

  friend class Garbage;

  CA(int i, int j){printf("主類構造函數運行: %d %dn", i, j);}

  ~CA(){printf("主類析構函數運行,結束了哦n");}

  static CA *m_instance;

  };

  CA *CA::m_instance = NULL;

  CA::Garbage CA::m_garbage(2, 3);

  int main()

  {

  CA *cmb = CA::GetInstance();

  cmb->Print();

  return 0;

  }

copyright © 萬盛學電腦網 all rights reserved