中級 › undefined reference to 'Class::member' の原因と直し方(staticメンバ変数) › パターン3
undefined reference to 'Class::member' の原因と直し方(staticメンバ変数)
クラス内でstaticメンバ変数を宣言しただけで、クラスの外側での実体定義を書き忘れたときにリンクの段階で出るエラーです。
1 #include <iostream> 2 class Id { 3 public: 4 static int next; 5 Id() { id = next; next++; } 6 int id; 7 }; 8 ____________________ ^ 9 int main() { 10 Id a, b; 11 std::cout << b.id << std::endl; 12 return 0; 13 }
undefined reference to `Id::next'
空欄を埋めてコンパイル・実行を通す
staticメンバ変数の実体定義はクラス定義の外側、通常はグローバルスコープに1行書くだけで済みます。
次の問題