ホームに戻る
 シングルトンなクラス

/*
*
*   シングルトンなクラス
*
*   シングルトンなクラスは常に1つのインスタンスを保持する。
*   新たなインスタンスを作成することはできない。
*   C++の仕様ではなく、仕様を利用して作成した構造である。
*
*/

#include <stdio.h>

// Singleton なクラス
class A{
  private:
    int x;
    static A *a;
    A(){x=3;};
  public:
    static A *get_instance(){
      if(a == NULL){
        a = new A();
      }

      return a;
    }
    void setX(int n){x=n;}
    void printX(){printf("print:x=%d\n", x);}
};

A* A::a = NULL;

int main(){
  //A a1;             //これはエラー
  //A *pb = new A();  //これもエラー

  A *pb = A::get_instance();

  pb->printX();
  pb->setX(4);

  pb = A::get_instance();

  pb->printX();

  getchar();

  return 0;
}


 結果

3
4

inserted by FC2 system