error: expected ';' after class definition の原因と直し方
クラス定義の閉じ波括弧}の後にセミコロンを書き忘れたときに出るエラーです。C++特有の落とし穴で、if文や関数定義の}にはセミコロンは要りませんが、クラスや構造体の定義には必要です。
エラーメッセージの読み方
main.cpp:5:2: error: expected ';' after class definition
main.cpp- ファイル名
5- 行番号
2- 列番号 — この位置でg++が構文解析に失敗しました
expected ';' after class definition- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 #include <iostream> 2 class Point { 3 public: 4 int x; 5 } ^ 6 int main() { 7 Point p; 8 p.x = 1; 9 std::cout << p.x << std::endl; 10 return 0; 11 }
main.cpp:5:2: error: expected ';' after class definition
if文や関数定義の}にはセミコロンは要りませんが、クラス定義は文の一種として扱われ、末尾に;が必要です。
直し方: (空) を ; にします。
広告
広告スロット(未設定)
パターン2
1 #include <iostream> 2 class Box { 3 public: 4 int size; 5 } ^ 6 int main() { 7 Box b; 8 b.size = 5; 9 std::cout << b.size << std::endl; 10 return 0; 11 }
main.cpp:5:2: error: expected ';' after class definition
クラス定義の}のあとに何も書かず次のコードが続くと、コンパイラはそこにセミコロンが無いことをエラーとして報告します。
直し方: (空) を ; にします。
パターン3
1 #include <iostream> 2 class Car { 3 public: 4 int speed; 5 } ^ 6 int main() { 7 Car c; 8 c.speed = 60; 9 std::cout << c.speed << std::endl; 10 return 0; 11 }
main.cpp:5:2: error: expected ';' after class definition
C言語には無いC++特有のルールなので、C言語の経験があるとかえって見落としやすいミスです。
直し方: (空) を ; にします。
よくある誤解
「波括弧で閉じるブロックはどれも同じルール」というのは誤解です。クラス・構造体・共用体・列挙型の定義は文の一種として扱われ、末尾にセミコロンが必要です。一方、関数定義やif/forなどの制御構文の}にはセミコロンは不要です。
まとめ
error: expected ';' after class definitionは中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。