Semicolon after class declaration braces(类声明大括号后的分号)
问题描述
在 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.
这篇关于类声明大括号后的分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:类声明大括号后的分号


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01