gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:54:03 26 4
gpt4 key购买 nike

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 thenamespace, and names introduced by these declarations into thedeclarative region of the namespace are said to be member names of thenamespace. A namespace member name has namespace scope. Its potentialscope includes its namespace from the name’s point of declaration(6.4.2) onwards; and for each using-directive (9.8.3) that nominatesthe member’s namespace, the member’s potential scope includes thatportion of the potential scope of the using-directive that follows themember’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 inan inline namespace includes the potential scope that name would haveif 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com