Cplusplus-cpp-static-members
提供:Dev Guides
C ++クラスの静的メンバー
*static* キーワードを使用して、クラスメンバーを静的に定義できます。 クラスのメンバーを静的として宣言すると、クラスのオブジェクトがいくつ作成されても、静的メンバーのコピーは1つしかありません。
静的メンバーは、クラスのすべてのオブジェクトによって共有されます。 他の初期化が存在しない場合、最初のオブジェクトが作成されると、すべての静的データはゼロに初期化されます。 クラス定義に入れることはできませんが、次の例のように、スコープ解決演算子 :: を使用して静的変数を再宣言することにより、クラスの外部で初期化できます。
私たちは、静的データメンバーの概念を理解するために、次の例を試してみましょう-
#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
//Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
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
};
//Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
Box Box1(3.3, 1.2, 1.5); //Declare box1
Box Box2(8.5, 6.0, 2.0); //Declare box2
//Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0;
}
上記のコードをコンパイルして実行すると、次の結果が生成されます-
Constructor called.
Constructor called.
Total objects: 2
静的関数メンバー
関数メンバーを静的として宣言することにより、クラスの特定のオブジェクトから独立させます。 クラスのオブジェクトが存在せず、クラス名とスコープ解決演算子 :: のみを使用して static 関数にアクセスする場合でも、静的メンバー関数を呼び出すことができます。
静的メンバー関数は、クラス外から静的データメンバー、他の静的メンバー関数、およびその他の関数にのみアクセスできます。
静的メンバー関数にはクラススコープがあり、クラスの this ポインターにアクセスできません。 静的メンバー関数を使用して、クラスのオブジェクトが作成されているかどうかを判断できます。
静的関数メンバーの概念を理解するために、次の例を試してみましょう-
#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
//Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
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
};
//Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
//Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); //Declare box1
Box Box2(8.5, 6.0, 2.0); //Declare box2
//Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
}
上記のコードをコンパイルして実行すると、次の結果が生成されます-
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2