为什么可以访问范围外的枚举数,而不能直接访问结构的成员?范围是指声明范围 - 如果我错了请纠正我。
举个例子: 你可以这样做:
enum colors {red, blue, white};
int color = red;
但是你不能这样做:
struct colors {red, blue, white};
int color = red;
谢谢!
最佳答案
好吧,正如另一条评论所说,这是因为这就是 C++ 的工作方式。
在过去,我们用类似的东西来模拟这样的东西
class Colors {
public:
static int RED = 0;
static int GREEN = 1;
static int YELLOW = 2;
}
然后添加了枚举,所以你不需要写 Colors.RED
.它本质上是语法糖。
更新
范围 只是程序中名称可见的部分。规则可以简单、复杂或怪异:C++ 适合复杂,JavaScript 适合怪异。可以看到冗长的解释here和 here ,但这是一个基本概念。
在 C++ 中,这是一种源自 Algol 60 的 block 结构语言,名称在声明它的 block 中定义。一种 block 是文件。如果在文件顶部声明了一个名称,则它会在声明之后的文件中随处定义。
另一种 block 由一对大括号定义{}
.大括号内声明的任何内容都是从声明到封闭的结束大括号定义的。所以
#include <stdlib> // copies a bunch of code into the file
int foo = 0; // declared here, visible to end.
int fn(){
int bar = 2 ;
if(bar == 2){
foo = bar;
cout << bar << nl; // gives '2'
cout << foo << nl; // still gives '2'
}
cout << foo << nl ; // gives '0'
cout << bar << nl ; // compile time error 'bar' not defined
}
为什么?内部foo
隐藏外层 foo
,所以这就是打印在 if
中的那个堵塞。 bar
定义在 if
的顶部 block ,因此它在结束 if
的大括号后不再可见(“不再在范围内”) block
还有更多规则,但我建议阅读其中一个链接或一本优秀的 C++ 书籍。
关于c++ - 为什么可以访问作用域外的枚举数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43826202/