gpt4 book ai didi

c++ - C 与 C++ 中的枚举范围

转载 作者:IT老高 更新时间:2023-10-28 22:00:24 26 4
gpt4 key购买 nike

为什么枚举值可以在 C 中定义的 block 之外访问,而在 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;
}

[Error] 'INT' was not declared in this scope

C 和 C++ 中的枚举和作用域规则是否不同?

最佳答案

在 C 中,对于枚举和结构的作用域根本没有规则。定义枚举的地方并不重要。

在 C++ 中,在另一个东西中定义一些东西(如类中的枚举)使这个东西属于另一个东西。

如果你想让你的枚举在 C++ 中是全局的,你必须在你的类之外定义它,或者从你的结构路径访问:

#include <iostream>
struct mystruct
{
enum {INT, FLOAT, STRING} type;
int integer;
float floating_point;
} tu;

int main()
{
tu.type = mystruct::INT; // INT is not in global scope, I have to precise it.
tu.integer = 100;
return 0;
}

注意:这在本例中有效,因为您使用的是 struct,默认情况下所有内容都是 public。当心;仅当枚举位于 public 范围内时,您才能从结构或类外部访问枚举类型和值,就像任何字段或函数一样。

关于c++ - C 与 C++ 中的枚举范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30047021/

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