gpt4 book ai didi

c++ - 两个未命名的命名空间,在同一个声明区域中定义

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:43 26 4
gpt4 key购买 nike

考虑以下代码:

#include<iostream>

namespace
{
int a = 5;
}

namespace
{
int a = 5;
}
int main()
{
int i=5;
{
std::cout << i;
}
}

此代码无效。这是因为发生了a的重定义。但我希望这是有效的。实际上,秒。 3.3.6/1 说:

[...]The potential scope denoted by an original-namespace-name is the concatenation of the declarative regions established by each of the namespace-definitions in the same declarative region with that original-namespace-name.[...]

但未命名的命名空间定义不是原始命名空间定义和 sec。 7.3.1/1 说:

namespace-name:
original-namespace-name
namespace-alias
original-namespace-name:
identifier

original-namespace-definition:
inline_opt namespace identifier { namespace-body }

此外,秒。 7.3.1.1 说:

An unnamed-namespace-definition behaves as if it were replaced by

inlineopt namespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }

where inline appears if and only if it appears in the unnamed-namespace-definition, all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the entire program.

这意味着两个未命名的命名空间具有不同的唯一性

你能解释一下我引用的代码中的行为吗?

最佳答案

它就在你引用的那篇文章中:

all occurrences of unique in a translation unit are replaced by the same identifier

因此翻译单元中所有未命名的命名空间都是相同的。

关于c++ - 两个未命名的命名空间,在同一个声明区域中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24409996/

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