c++ - 命名空间作用域在 C++ 中是如何工作的?

标签 c++ namespaces language-lawyer

C++ ISO 草案 2020(6.4.6 Namespace Scope) 在第一段中的引用(我加粗):

The declarative region of a namespace-definition is its namespace-body . Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace. A namespace member name has namespace scope. Its potential scope includes its namespace from the name’s point of declaration (6.4.2) onwards; and for each using-directive (9.8.3) that nominates the member’s namespace, the member’s potential scope includes that portion of the potential scope of the using-directive that follows the member’s point of declaration.


我认为未命名和命名命名空间之间没有区别,但是以下代码有问题:
#include <iostream>
namespace A {int a = 1;}
namespace {int b = 1;}
void main() {
    std::cout << a; // identifier "a" is undefined
    std::cout << b;
}
Cppreference给出了这个问题的原因:

The potential scope of a name declared in an unnamed namespace or in an inline namespace includes the potential scope that name would have if it were declared in the enclosing namespace.


但根据我对这个问题第一句话的理解,这个错误不应该发生。这里发生了什么?

最佳答案

I thought it wouldn't have a difference between unnamed and named namespace


两者 ab可在 main 购买.但是a没有作用域解析就无法访问。文档中提到了“潜在作用域”、“实际作用域”和“作用域”,加上块/类/函数/命名空间作用域,可能会让人感到困惑。
您可以看到命名和未命名的相似性namespace使用此代码:
class foo
{
    std::string str;
public:
    foo(const char* s) { str = s; cout << str << " foo()\n"; }
    ~foo() { cout << str << " ~foo()\n"; }
};

namespace named { foo a("named"); }
namespace { foo b("unnamed"); }
int main()
{
    cout << "start\n";
    named::a;
    b;
    cout << "end\n";
    return 0;
}

关于c++ - 命名空间作用域在 C++ 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69600721/

相关文章:

c++ - 动态对象析构函数中的异常

c++ - 使用结构作为参数 : Error: Struct not defined

c++ - 发布版本不起作用 - Eigen 库出错?

c# - 在类之间共享枚举

c - 复合文字的生命周期

c++ - 比较分别从容器中获取的迭代器是否有效?

c++ - 一个类可以共享一个命名空间的名称吗?

scala - 如何更改 Lift 项目根包?

jvm - JVM 操作数栈必须是确定性的吗?

c++ - 为什么允许某些非常量表达式作为 constexpr 逗号运算符的操作数?