gpt4 book ai didi

c++ - 声明名称、引入名称和声明实体的区别

转载 作者:可可西里 更新时间:2023-11-01 18:35:38 27 4
gpt4 key购买 nike

来自 C++11 标准,§7.3.3[namespace.udecl]/1:

A using-declaration introduces a name into the declarative region in which the using-declaration appears.

using-declaration:

using typenameopt nested-name-specifier unqualified-id ;
using :: unqualified-id ;

using 声明中指定的成员名称在出现 using 声明的声明区域中声明。

在 using 声明发生的声明区域中声明的名称是什么意思?

这是否与将该名称引入出现 using 声明的声明区域相同?

还有声明名称和声明名称表示的实体之间有区别吗?

例子:

namespace N { static int i = 1; } /* Declares an entity denoted by 
the name i in the declarative region of the namespace N.
Introduces the name into the declarative region of the namespace N.
Declares the name i in the declarative region of the namespace N? */
using N::i; /* Declares the name i in the declarative region of the
global namespace. Also introduces that name into the declarative
region of the global namespace? Also declares the entity that the
name i denotes? */

最佳答案

根据第一原则,一个实体是,来自[basic]

a value, object, reference, function, enumerator, type, class member, bit-field, template, template specialization, namespace, parameter pack, or this. [...] Every name that denotes an entity is introduced by a declaration.

声明声明事物。被声明意味着它是由声明引入的,来自[basic.scope.declarative]

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity.

The names declared by a declaration are introduced into the scope in which the declaration occurs, except that the presence of a friend specifier (11.3), certain uses of the elaborated-type-specifier (7.1.6.3), and using-directives (7.3.4) alter this general behavior.

这些异常在这里都不相关,因为我们谈论的是using-declarations 而不是using-directives。让我稍微修改一下您的示例,以避免使用全局命名空间:

namespace N {        //  + declarative region #1
// |
static int i; // | introduces a name into this region
// | this declaration introduces an entity
} // +

首先,N::i 是在命名空间 N 中声明并引入到 N 范围内的实体。现在,让我们添加一个using-declaration:

namespace B {        //  + declarative region #2
// |
using N::i; // | declaration introduces a name i
// | but this is not an entity
} // +

从 [namespace.udecl],我们有:

If a using-declaration names a constructor (3.4.3.1), it implicitly declares a set of constructors in the class in which the using-declaration appears (12.9); otherwise the name specified in a using-declaration is a synonym for a set of declarations in another namespace or class.

using-declaration using N::i 没有命名构造函数,因此 i 不是一个新实体,它是 N::i同义词

所以基本上,i 都是在各自的命名空间中引入和声明的名称。在 N 中,i 声明了一个具有静态链接的实体,但在 B 中,i 声明了该实体的同义词- 不是新实体。

关于c++ - 声明名称、引入名称和声明实体的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708705/

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