gpt4 book ai didi

c++ - C++ 标准中 [basic.scope.hiding] 中的 "same scope"到底意味着什么?

转载 作者:行者123 更新时间:2023-12-03 02:40:51 24 4
gpt4 key购买 nike

在 C++14 标准中,[basic.scope.hiding],第 2 段 (3.3.10.2) 说:

A class name or enumeration name can be hidden by the name of a variable, data member,function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

我对“同一范围”这个措辞感到不安。事实上,在下面的代码片段中,类 C 和变量 C 声明在同一作用域中的情况是什么?

namespace case_1 {
int C;
class C;
// Here C refers to variable
}

namespace case_2 {
class C;

namespace nested {
int C;
// Here C refers to variable
}
}

namespace case_3 {
int C;

namespace nested {
class C;
// Here C refers to class
}
}

namespace case_4 {
enum Enum { A, B, C };
class C;
// Here C refers to enumerator
}

假设1:“相同作用域”意味着“相同 block ”

如果我们坚持这个假设,情况 1 应该受到规则 3.3.10.2 的关注。案例2呢?我猜规则 3.3.10.1 涵盖了它:

A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class.

此外,这个假设很好地解释了情况 3,其中类名隐藏了变量名称(而不是相反),但无法解释情况 4。事实上,C 枚举器是在与 C 类不同的 block ,但该类仍然是隐藏的。

假设2:“在相同范围内声明”意味着“具有完全相同的范围”

如果该假设成立,则我的代码中描述的任何情况都不会受到该规则的影响,因为两个名称不可能具有完全相同的范围。即使 case_1 中的变量也具有与类不同的作用域。事实上,变量名的范围在其声明之后开始,因此在类名之前开始。

假设3:“在同一范围内声明”意味着“其中一个名称在另一个名称的范围内声明”

如果这个假设成立,则规则 3.3.10.2 应该涵盖上述所有情况。事实上,在 case_1case_3 中,C 类是在 C 变量的作用域中声明的;在 case_2 中,C 变量在 C 类的作用域中声明;并且,在 case_4 中,C 类在 C 枚举器的范围内声明。但是,case_3 不遵循规则,因为它是应该“获胜”并保持可见的变量。

<小时/>

正如您所看到的,我的每个假设都有一个缺点,我真的不明白该标准中该段落中“相同范围”的确切含义。

最佳答案

what are the cases where the class C and the variable C are declared in the same scope?

情况 1 和 4 的范围相同。情况 2 和情况 3 不是同一范围。

在这种情况下,我确实无法在“相同”的标准中找到准确的定义,但有意义且与测试结果相匹配的解释是比较最小封闭范围(或者更确切地说,每个声明的声明区域1)。

Hypothesis 1: "same scope" means "same block"

虽然 block 有作用域,但它们并不等同。例如,还有命名空间作用域和类作用域。

but can't explain the case 4. Indeed, C enumerator is declared in a different block than C class but the class is still hided.

枚举声明没有范围。枚举器和类在同一范围内。

Hypothesis 2: "declared in the same scope" means "have exactly the same scope"

正如您所说,没有一个声明可以与另一个声明具有完全相同的范围,因此这种解释将使规则变得毫无意义。

Hypothesis 3: "declared in the same scope" means "one of the name is declared inside the scope of the other"

这不是正确的解释,因为嵌套范围可以在一个声明的范围内,但就相关规则而言,它不是同一范围。

<小时/>

1 在最新的标准草案中,措辞已更改为使用术语“声明性区域”,这显然与“范围”的含义略有不同。但它并没有改变规则的预期含义。

关于c++ - C++ 标准中 [basic.scope.hiding] 中的 "same scope"到底意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58220269/

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