类声明括号后的分号 [英] Semicolon after class declaration braces

查看:107
本文介绍了类声明括号后的分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++类中,为什么在右花括号后加分号?我经常忘记它并得到编译器错误,从而浪费时间.在我看来似乎是多余的,情况不太可能.人们真的会做类似的事情吗?

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 unlikely to be the case. Do people really do things like:

class MyClass
{
.
.
.
} MyInstance;

我从C结构和枚举的C兼容性角度获得了它,但是由于类不是C语言的一部分,我想它主要是在相似的声明结构之间保持一致性.

I get it from a C compatibility point of view for structs and enums, but since classes aren't part of the C language I guess it's primarily there the keep consistency between similar declaration constructs.

我一直在寻找的是与设计原理相关的东西,而不是能够更改任何内容,尽管良好的代码完成IDE可能会在编译之前就将其捕获.

What I was looking for was more related to design rationale rather than being able to change anything, although a good code completion IDE might trap this before compilation.

推荐答案

语言需要在类型声明中的右花括号后加分号.自最早的C版本以来就是这种方式.

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; };
}

在这种情况下,我认为很清楚为什么需要分号.至于为什么我不确定在头文件中声明的更一般情况下为什么需要它.我的 guess 是它的历史悠久,并且可以简化编写编译器的过程.

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.

这篇关于类声明括号后的分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆