考虑以下计划:
#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';
}
即使我在gcc和clang中都使用-pedantic-errors
选项,程序编译也很好。 (请参阅现场演示here和here。)如果我将分号放在geta()成员函数的末尾,我也不会从编译器中得到任何错误,如下所示:
int geta()
{
return a;
}; // This also compiles fine without any error or warnings in both g++ & clang
那么,允许这个不必要的分号的目的是什么?这有什么用吗?它是否被语言标准明确允许?
分号(;)代表c ++中的空声明。你可以看到Declarations
C ++类允许在大括号内部执行以下操作:
参考:Class
因此按照上述规则,c ++中允许空声明。这就是你有分号的原因。