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
两者
a
和 b
可在 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/