为什么 C++ 的类/结构体/联合体/枚举 的}后面要写;,而函数定义不用?
引言
相信大多数人都遇到以下的编译错误:
error: expected ';' after class definition
error: expected ';' after struct definition
error: expected ';' after union definition
error: expected unqualified-id at end of input
在Stack Overflow等社区也有相关的不少讨论:
- Semicolon after class declaration braces
- Semicolon after Function
- When do we need to put semicolon after curly brackets?
- Shall a C++ class function end with a }; or only a }?
some people put Semicolon always, because they don't want to remember when it is necessary
btw:在
Java和C#中,类声明语法是不需要“尾随分号”的。
原因
显然,这种规则是从C继承过来的,在C语言中,可以在定义结构体之后立即声明对象,和int a = 1;是同样的简单声明:
void Example() {
struct { int x; } s1;
s1.x = 42;
struct ADifferentType { int x; };
}
立即声明对象的一个好处是可以实现匿名类的对象。
在早期的C版本中,除非另有声明,函数默认隐式返回int类型。若在结构体定义末尾省略分号,例如:
struct fred { int x; long y; }
main()
{
return 0; /* invalid return type, expected fred type */
}
这里我们不仅定义了一个新类型fred,还声明了将返回一个fred类型的实例的main函数。
语法
class|struct|union|enum 这类属于是Simple declaration:
Simple declaration
A simple declaration introduces, creates, and optionally initializes identifiers (typically variables).decl-specifier-seq init-declarator-list /* optional */ ; attr decl-specifier-seq init-declarator-list ; // since C++11
decl-specifier-seq— sequence of specifiersinit-declarator-list— comma-separated list of init-declaratorattr— sequence of attributes
ctor-initializer (optional) compound-statement
: Regular function body.
function-try-block
: Function try block.
= default ;
: Explicitly defaulted function definition(since C++11).
= delete ;
: Explicitly deleted function definition(since C++11).
= delete ( string-literal );
: Explicitly deleted function definition with error message (since C++26).
-
ctor-initializer - member initializer list, only allowed in constructors
-
compound-statement - the brace-enclosed sequence of statements that constitutes the body of a function
-
function-try-block - a function try block
-
string-literal - an unevaluated string literal that could be used to explain the rationale for why the function is deleted