在分类后声明括号 [英] Semi Colon after class declaration braces

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

问题描述

对于什么可能是一个愚蠢的问题提前道歉,但在C ++类中,为什么闭尾括号后的分号?我经常忘记它,并得到编译器错误,从而失去时间。似乎对我有点多余,这是不可能的情况。人们是否真的做了

Apologies in advance for what is probably a stupid question, but 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语言的一部分,我想它的主要是在类似的声明构造之间保持一致性。我正在寻找的是更多的相关的设计理由,而不是能够改变任何东西,虽然一个良好的代码完成IDE可能陷阱这在编译之前。

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



在这种情况下,我认为很清楚为什么需要分号。至于为什么在更一般的情况下需要在头文件中声明我不确定。我的猜测是它的历史,是为了使编写编译器更容易。

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天全站免登陆