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

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

问题描述

在 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 语言的一部分,我猜它主要是为了保持类似声明结构之间的一致性.

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

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

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