ホームに戻る
 staticメンバ変数とstaticメンバ関数

#include <iostream>

/*
*
*   staticメンバ変数とstaticメンバ関数
*
*   staticメンバはインスタンスの生成の関係無しに、
*   常に1つだけ存在します。
*
*   複数のオブジェクトが共有する1つの変数として、
*   利用することが可能です。
*
*   注意として、staticメンバ変数の初期化はヘッダ内で行うと、
*   複数のstaticメンバ変数が定義される原因となります。
*
*/

class A{
  static int num;  // staticメンバ変数
public:
  void setNum(int n){num = n;}
  static getNum(){return num;}  // staticメンバ関数
};

int A::num = 1;  // staticメンバ変数の初期化

using namespace std;

int main(){
  A *a = new A[2];

  cout << A::getNum() << endl;

  a[0].setNum(2);

  cout << A::getNum() << endl;

  a[1].setNum(3);

  cout << A::getNum() << endl;

  delete [] a;

  cout << A::getNum() << endl;  // delete [] したのに使える

  return 0;
}

 結果

1
2
3
3

inserted by FC2 system