Semicolon after class declaration braces

前端 未结 7 864
忘了有多久
忘了有多久 2020-11-29 20:17

In C++ classes, why the semi-colon after the closing brace? I regularly forget it and get compiler errors, and hence lost time. Seems somewhat superfluous to me, which is un

7条回答
  •  眼角桃花
    2020-11-29 20:57

    In C/C++ the ; is a statement terminator. All statements are terminated with ; to avoid ambiguity (and to simplify parsing). The grammar is consistent in this respect. Even though a class declaration (or any block for that matter) is multiple lines long and is delimited with {} it is still simply a statement (the { } is part of the statement) hence needs to be terminated with ; (The ; is not a separator/delimitor)

    In your example

    class MyClass{...} MyInstance;
    

    is the complete statement. One could define multiple instances of the declared class in a single statement

    class MyClass{...} MyInstance1, MyInstance2;
    

    This is completely consistent with declaring multiple instances of a primitive type in a single statement:

    int a, b, c;
    

    The reason one does not often see such desclaration of class and instance, is the instance could ?only? be a global variable, and you don't really often want global objects unless they are static and/or Plain Old Data structures.

提交回复
热议问题