函数参数列表中的类声明

9
据我理解,在C++中,函数参数列表内声明的类会自动进入封闭作用域。
void f(struct A *p) {}

void g() { A *p; f(p); }

相当于:

struct A;

void f(A *p) {}

void g() { A *p; f(p); }

C++标准的哪个部分规定了这种行为?C语言又是怎样的情况呢?

我猜测在这个问题上 C 语言没有遵循 C++ 的做法。在 Visual Studio 编译器中,当使用 C 模式时,它不会编译这段代码:

void g(struct A { int a; } a);

struct A a;     // 'a' uses undefined struct 'A'

1
你最后的例子在C++中也无法编译。 - molbdnilo
是的,我忘记注明C++不允许在函数参数列表中定义类。我的意思是,在这种情况下,C并不像C++那样将类声明在参数列表内会“泄漏”到函数声明范围内。 - igntec
1个回答

4

这是一个限定符。在C++14中,相关的引用如下:

[basic.lookup.elab]/2: [...] If the elaborated-type-specifier is introduced by the class-key and this lookup does not find a previously declared type-name, or if the elaborated-type-specifier appears in a declaration with the form:

class-key attribute-specifier-seqopt identifier ;

the elaborated-type-specifier is a declaration that introduces the class-name as described in 3.3.2.

这样声明类名:

[basic.scope.pdecl]/7: The point of declaration of a class first declared in an elaborated-type-specifier is as follows:

— [...]

— 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.

因为struct A是一个详细类型说明符,并且A之前没有被声明过,所以A会在包含声明的命名空间中声明(在这种情况下,是全局命名空间)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接