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.
这篇关于类声明大括号后的分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:类声明大括号后的分号
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01