中級 › staticメンバ変数の undefined reference の原因 › パターン4
staticメンバ変数の undefined reference の原因
クラス内でstaticメンバ変数を宣言しただけで、クラスの外側での実体定義を書き忘れたときにリンクの段階で出るエラーです。
1 #include <iostream> 2 class Inventory { 3 public: 4 static int total; 5 Inventory() { total++; } 6 }; 7 _________________________ ^ 8 int main() { 9 Inventory a, b, c; 10 std::cout << Inventory::total << std::endl; 11 return 0; 12 }
undefined reference to `Inventory::total'
空欄を埋めてコンパイル・実行を通す
クラス内のstatic宣言は実体を持たないため、クラスの外側で一度だけ定義する必要があります。
次の問題