gpt4 book ai didi

c++ - 类内外无作用域的枚举重定义

转载 作者:行者123 更新时间:2023-11-28 06:52:10 26 4
gpt4 key购买 nike

有来自 3.3.7/5 的例子:

typedef int c;
enum { i = 1 };
class X
{
char v[i]; // error: i refers to ::i
// but when reevaluated is X::i
int f() { return sizeof(c); } // OK: X::c
char c;
enum { i = 2 };
};

但它甚至无法编译。导致以下错误:

test.cpp:9:12: error: declaration of ‘i’ [-fpermissive]

test.cpp:4:8: error: changes meaning of ‘i’ from ‘ i’ [-fpermissive]

这个例子有什么意义?

最佳答案

这个例子演示了类作用域及其规则,特别是下面的规则

2) A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

在此示例中,名称 i 未在类范围内引用相同的名称。它首先引用全局枚举器 i,然后重新计算并引用类枚举器 i。

因此编译器会发出错误,尽管规则中写的是实现定义是否会有编译器诊断。

至于在函数f中的operator sizeof中使用名称c则指的是同名的类数据成员,因为按照规则

1) The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies

关于c++ - 类内外无作用域的枚举重定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23750766/

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