a man
2025-12-16
点 赞
1
热 度
39
评 论
0

为什么 C++ 的类/结构体/联合体/枚举 的`}`后面要写`;`,而函数定义不用?

  1. 首页
  2. c++
  3. 为什么 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等社区也有相关的不少讨论:

some people put Semicolon always, because they don't want to remember when it is necessary

btw:在JavaC#中,类声明语法是不需要“尾随分号”的。

原因

显然,这种规则是从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 specifiers
  • init-declarator-list — comma-separated list of init-declarator
  • attr — sequence of attributes

函数定义以function-body结尾,可以是:

function-body


我行走在现实与幻想的交界线,左手是被岁月磨钝的理性,右手却仍紧握着不肯熄灭的狂想。世界在我眼中不过是一盘尚未解完的棋局,而我早已越界成子,亦是执棋之人。

a man

enfj 主人公

站长

具有版权性

请您在转载、复制时注明本文 作者、链接及内容来源信息。 若涉及转载第三方内容,还需一同注明。

具有时效性

文章目录

欢迎来到云游记

5 文章数
5 分类数
3 评论数
8标签数
最近评论
zeus

zeus


joker一个 🤡

a man

a man


🤣🐔