c++ - 名称查找和声明点概念

标签 c++ namespaces

我对point of declarationname-lookup 概念之间的形式耦合很感兴趣。特别是,当 nested-name-specifier 表示命名空间时,非限定名称查找会产生一组声明,如下所示:N4296::3.4.3.2 [namespace.qual]

For a namespace X and name m, the namespace-qualified lookup set S(X,m) is defined as follows: Let S0(X,m) be the set of all declarations of m in X and the inline namespace set of X (7.3.1). If S0(X,m) is not empty, S(X,m) is S0(X,m); otherwise, S(X,m) is the union of S(Ni,m) for all namespaces Ni nominated by using-directives in X and its inline namespace set.

让我举几个例子:

1.

#include <iostream>

namespace A
{
    int b = 42;
}

int a = A::a; //Error

namespace A
{
    int a = 24;
}

int main(){ std::cout << a << std::endl; }

DEMO

2.

#include <iostream>

namespace A
{
    int b = 42;
}

namespace A
{
    int a = 24;
}

int a = A::a; //OK

int main(){ std::cout << a << std::endl; }

DEMO

我提供的规则与声明点概念无关,但实际上我们可以看到它确实如此。因此,标准隐含地假定名称的 m 声明点应该在使用名称的点之前。我认为应该明确指定。也许我丢失了指定它的子句...如果是这样,你能指出那个吗?

最佳答案

来自 [basic.scope.namespace] (§3.3.6/1),强调我的:

A namespace member name has namespace scope. Its potential scope includes its namespace from the name’s point of declaration (3.3.2) onwards

a 只能在命名空间 A 声明之后 中找到。所以示例 (1) 无效,因为 a 尚未声明,示例 (2) 有效,因为它已经声明。

关于c++ - 名称查找和声明点概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28163389/

相关文章:

php - 在 Laravel 中找不到类 'App\Http\Controllers\Excel'

c++ - 如何避免 GDB 中符号的命名空间前缀?

python - locals 字典是什么时候设置的?

c# - 如何在 Unity 编辑器中处理不可见的 c# 命名空间?

c++ - 0、int() 和 int{} 之间有什么区别?

c++ - 在 C++ 中如何对一组自变量应用相同的操作?

c++ - 在 QLayout 中创建和删除自定义 QWidgets 时出现 RAM 问题

c++ - 如何在 C++ 中正确返回数组(类成员)?

C++:类与命名空间的全局实例:RAM 使用情况?

c++ - 在 C++ 中重载增强赋值(返回类型)