導入
「インスタンスごとではなく、クラス全体で1つだけ持ちたい」データや関数があります。たとえば「これまで作った個数」。それを実現するのが static メンバです。
説明
static メンバ変数は、インスタンスをいくつ作ってもクラスに1つだけ存在し、全インスタンスで共有されます。クラス外で1度だけ実体を定義します。
flowchart TB s["static int count(クラスに1つ)"] a["インスタンス a"] --> s b["インスタンス b"] --> s c["インスタンス c"] --> s
#include <iostream>
using namespace std;
class Widget {
public:
static int count; // 宣言(全インスタンスで共有)
Widget() { count++; }
};
int Widget::count = 0; // 実体の定義(クラス外に1度だけ)
int main() {
Widget a, b, c;
cout << Widget::count << endl; // 3(作った個数)
return 0;
}
static メンバ関数は、特定のインスタンスに属さない関数です。this を持たず、static メンバや引数だけを使えます。呼び出しは クラス名::関数名() です。
#include <iostream>
using namespace std;
class MathUtil {
public:
static int square(int x) { // インスタンス不要の関数
return x * x;
}
};
int main() {
cout << MathUtil::square(5) << endl; // 25(インスタンスを作らず呼べる)
return 0;
}
まとめ
static メンバは「クラスに1つだけ・全インスタンスで共有」。個数のカウントや、共通の定数・ユーティリティ関数に使います。static メンバ関数はインスタンスなしで クラス名:: で呼べます。