gpt4 book ai didi

c++ - 函数参数列表中的类声明

转载 作者:可可西里 更新时间:2023-11-01 16:42:03 25 4
gpt4 key购买 nike

据我所知,在 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'

最佳答案

这是一个精心设计的类型说明符。 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 是一个elaborated-type-specifier 并且 A 之前没有声明过,A 在包含声明的命名空间(在本例中为全局命名空间)中声明。

关于c++ - 函数参数列表中的类声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37744047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com