在类定义中允许不必要的分号的目的

Des*_*tor 4 c++ syntax

考虑以下计划:

#include <iostream>
struct Test
{
    int a;
    Test(int s) : a(s)
    { };        // Observe this semicolon
    int geta()
    {
        return a;
    }
};
int main()
{
    Test t(3);
    std::cout<<t.geta()<<'\n';
}
Run Code Online (Sandbox Code Playgroud)

即使我-pedantic-errors在gcc和clang中都使用了选项,程序编译也很好.(请参阅此处此处的实时演示.)如果我在geta()成员函数的末尾添加分号,我也不会从编译器中得到任何错误,如下所示:

int geta()
{
   return a;
}; // This also compiles fine without any error or warnings in both g++ & clang
Run Code Online (Sandbox Code Playgroud)

那么,允许这个不必要的分号的目的是什么?这有什么用吗?它是否被语言标准明确允许?

Ris*_*ani 7

分号(;)代表c ++中的空声明.你可以看到声明

C++类允许在大括号内部执行以下操作:

  • 访问说明符列表
  • 成员对象
  • 成员函数声明和定义
  • 参考:

    因此按照上述规则,c ++中允许空声明.这就是你有分号的原因.