Class 函数声明中的声明

Class declaration within a function declaration

考虑以下示例:

#include <iostream>

void foo(class B, B *b); 

B *c; //OK

int main(){ }

DEMO

标准N4296::3.3.2/7.1 [basic.scope.pdecl]

— for a declaration of the form

class-key attribute-specifier-seqopt identifier;

the identifier is declared to be a class-name in the scope that contains the declaration

,但根据 N4296:3.3.4/1 [basic.scope.proto]

In a function declaration, or in any function declarator except the declarator of a function definition (8.4), names of parameters (if supplied) have function prototype scope, which terminates at the end of the nearest enclosing function declarator.

所以,class B 应该在函数原型作用域中引入。 B 的范围应该一直到 foo 的声明符的末尾。但是名称在全局范围内是可见的。为什么?

您在 3.3.2 [basic.scope.pdecl]/p7 中引用了错误的项目符号。 foo 声明中的 class B 不是 class-key attribute-specifier-seq_opt identifier; 的形式 - 没有分号。

相反,第二个项目符号适用:

for an elaborated-type-specifier of the form

class-key identifier

if the elaborated-type-specifier is used in the decl-specifier-seq or parameter-declaration-clause of a function defined in namespace scope, the identifier is declared as a class-name in the namespace that contains the declaration; otherwise, except as a friend declaration, the identifier is declared in the smallest namespace or block scope that contains the declaration.

因此,您示例中的 elaborated-type-specifier class BB 声明为 class-包含 foo 声明的命名空间中的 name - 即全局命名空间。