【发布时间】:2015-05-05 07:46:51
【问题描述】:
为什么枚举值可以在 C 中定义的块之外访问,而在 C++ 中却不能?
考虑以下 C 程序。
#include <stdio.h>
struct mystruct
{
enum {INT, FLOAT, STRING} type;
int integer;
float floating_point;
} tu;
/* Why is INT accessible here? */
int main()
{
tu.type = INT;
tu.integer = 100;
return 0;
}
它在 C 中编译并运行良好。
但在 C++ 中编译失败。
#include <iostream>
struct mystruct
{
enum {INT, FLOAT, STRING} type;
int integer;
float floating_point;
} tu;
/* Why is INT accessible here? */
int main()
{
tu.type = INT;
tu.integer = 100;
return 0;
}
[错误] 'INT' 未在此范围内声明
C 和 C++ 中的枚举和作用域规则是否不同?
【问题讨论】:
-
了解“命名空间”
-
@meet C++ 具有类作用域。看我的回答。