Semicolon after class declaration braces

前端 未结 7 858
忘了有多久
忘了有多久 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:42

    The semi-colon after the closing brace in a type declaration is required by the language. It's been that way since the earliest versions of C.

    And yes, people do indeed do the declaration you just put up there. It's useful for creating scoped types inside of methods.

    void Example() {
      struct { int x; } s1;
      s1.x = 42;
    
      struct ADifferentType { int x; };
    }
    

    In this case, I think it's clear why the semi-colons are needed. As to why it's needed in the more general case of declaring in the header file I'm unsure. My guess is that it's historical and was done to make writing the compiler easier.

提交回复
热议问题