問題描述
在 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.
這篇關于類聲明大括號后的分號的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!