D-programming-static-members

提供:Dev Guides
移動先:案内検索

Dプログラミング-クラスの静的メンバー

staticキーワードを使用して、クラスメンバー static を定義できます。 クラスのメンバーを静的として宣言すると、クラスのオブジェクトがいくつ作成されても、静的メンバーのコピーは1つしかありません。

静的メンバーは、クラスのすべてのオブジェクトによって共有されます。 他の初期化が存在しない場合、最初のオブジェクトが作成されると、すべての静的データはゼロに初期化されます。 それをクラス定義に入れることはできませんが、スコープ解決演算子::を使用して静的変数を再宣言することにより、クラスの外側で初期化できます。

私たちは、静的データメンバーの概念を理解するために、次の例を試してみましょう-

import std.stdio;

class Box {
   public:
      static int objectCount = 0;

     //Constructor definition
      this(double l = 2.0, double b = 2.0, double h = 2.0) {
         writeln("Constructor called.");
         length = l;
         breadth = b;
         height = h;

        //Increase every time object is created
         objectCount++;
      }

      double Volume() {
         return length *breadth* height;
      }

   private:
      double length;    //Length of a box
      double breadth;   //Breadth of a box
      double height;    //Height of a box
};

void main() {
   Box Box1 = new Box(3.3, 1.2, 1.5);   //Declare box1
   Box Box2 = new Box(8.5, 6.0, 2.0);   //Declare box2

  //Print total number of objects.
   writeln("Total objects: ",Box.objectCount);
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Constructor called.
Constructor called.
Total objects: 2

静的関数メンバー

関数メンバーを静的として宣言することにより、クラスの特定のオブジェクトから独立させます。 クラスのオブジェクトが存在せず、クラス名とスコープ解決演算子::のみを使用して static 関数にアクセスする場合でも、静的メンバー関数を呼び出すことができます。

静的メンバー関数は、静的データメンバー、他の静的メンバー関数、およびクラス外からのその他の関数にのみアクセスできます。

静的メンバー関数にはクラススコープがあり、クラスの this ポインターにアクセスできません。 静的メンバー関数を使用して、クラスのオブジェクトが作成されているかどうかを判断できます。

静的関数メンバーの概念を理解するために、次の例を試してみましょう-

import std.stdio;

class Box {
   public:
      static int objectCount = 0;

     //Constructor definition
      this(double l = 2.0, double b = 2.0, double h = 2.0) {
         writeln("Constructor called.");
         length = l;
         breadth = b;
         height = h;

        //Increase every time object is created
         objectCount++;
      }

      double Volume() {
         return length *breadth* height;
      }

      static int getCount() {
         return objectCount;
      }

   private:
      double length;    //Length of a box
      double breadth;   //Breadth of a box
      double height;    //Height of a box
};

void main() {
  //Print total number of objects before creating object.
   writeln("Inital Stage Count: ",Box.getCount());

   Box Box1 = new Box(3.3, 1.2, 1.5);   //Declare box1
   Box Box2 = new Box(8.5, 6.0, 2.0);   //Declare box2

  //Print total number of objects after creating object.
   writeln("Final Stage Count: ",Box.getCount());
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Inital Stage Count: 0
Constructor called.
Constructor called
Final Stage Count: 2