用户声明的名称空间成员 [英] User-declared namespace member
问题描述
从3.4.1/14开始存在
There is from 3.4.1/14:
如果命名空间的变量成员在以下范围之外定义 它的名称空间,然后出现在定义中的任何名称 查找成员(在declarator-id之后),好像 该成员出现在其命名空间中.
If a variable member of a namespace is defined outside of the scope of its namespace then any name that appears in the definition of the member (after the declarator-id) is looked up as if the definition of the member occurred in its namespace.
如果该名称被视为成员名称的定义,那么声明的重点是什么?
以及以下示例为何起作用:
And why the following example will works:
namespace N
{
extern int j;
}
int i = 2;
int N::j = i; //N::j=2
int N::j=i
实际出现在名称空间范围内.因此,对于不合格的名称查找,声明int i=2
不可见. 为什么找到此声明?
int N::j=i
actual appears into the namespace scope. Hence the declarationint i=2
is not visible for unqualified name lookup. Why does this declaration found?
推荐答案
您的问题:
int N::j=i
实际出现在名称空间范围内.因此,对于不合格的名称查找,声明int i=2
不可见.为什么找到此声明?
int N::j=i
actual appears into the namespace scope. Hence the declarationint i=2
is not visible for unqualified name lookup. Why does this declaration found?
答案:
由于在
N
命名空间中找不到i
,因此将在全局命名空间中进行查找.如果在N
名称空间中有一个i
,该名称将用于初始化N::j
.
Since
i
is not found in theN
namespace, it is looked up in the global namespace. Had ani
been there in theN
namespace, that would have been used to initializeN::j
.
希望以下程序可以澄清您的疑问.
Hope the following program clarifies your doubt.
#include <iostream>
namespace N
{
extern int j;
extern int k;
int x = 3;
}
int x = 2;
int y = 10;
int N::j = x; // N::x is used to initialize N::j
int N::k = y; // ::y is used to initialize N::k
int main()
{
std::cout << N::j << std::endl;
std::cout << N::k << std::endl;
}
输出:
3
10
更新,以回应OP的评论
标准所说的是:
namespace N
{
extern int j;
}
int x = 2;
int N::j = x;
等效于:
namespace N
{
extern int j;
}
int x = 2;
namespace N
{
int j = x;
}
x
的查找逻辑是相同的.如果在同一名称空间N
中找到它,则使用它.如果在名称空间N
中找不到x
,则会在封闭的名称空间中向外搜索.
The logic for lookup ofx
is same. If it is found within the same namespace N
, it is used. If x
is not found in namespace N
, it is searched for outward in the enclosing namespaces.
这篇关于用户声明的名称空间成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!