c – 声明名称,引入名称和声明实体之间的区别

前端之家收集整理的这篇文章主要介绍了c – 声明名称,引入名称和声明实体之间的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从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声明的声明性区域相同?

声明名称和声明名称所代表的实体之间是否有区别?

例:

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? */

解决方法

从第一原则来看,一个实体来自[基础]

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.

这些例外都不相关,因为我们讨论的是使用声明而不是使用指令.让我稍微改变你的例子,以避免全局命名空间:

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

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

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.

使用N :: i的using声明没有命名构造函数,因此它不是名称i是新实体,而是N :: i的同义词.

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

猜你在找的C&C++相关文章