C vs C ++中的枚举范围 [英] Scope of enum in C vs C++

查看:151
本文介绍了C vs C ++中的枚举范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C中定义了枚举但不能在C ++中定义的块之外可以访问枚举值?

Why are enum values accessible outside the block in which enum is defined in C, but not in 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中编译并正常运行。

It compiles and runs fine in C.

但是在C ++中,编译失败。

But in C++ it fails in compilation.

#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'在这个范围内

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

在C和C ++中枚举和范围规则是否不同?

Are enum and scope rules different in C and C++?

推荐答案

在C语言中,枚举和结构的作用域根本没有规则。定义枚举的位置没有任何意义。

In C, there is simply no rule for scope for enums and struct. The place where you define your enum doesn't have any importance.

在C ++中,在另一个内部定义事物(例如类中的枚举)使该事物属于

In C++, define something inside another something (like an enum in a class) make this something belong to the another something.

如果要在C ++中将枚举全局化,则必须在类外定义它,或者从结构路径访问它:

If you want to make your enum global in C++, you will have to define it outside your class, or access from your struct path:

#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;
}

注意:在此示例中有效,因为您使用的是结构,默认情况下所有内容都是 public 。小心;仅当枚举位于 public 范围内(如任何字段或函数)时,才可以从结构或类外部访问枚举类型和值。

Note: This works in this exemple, because you are using a struct, where everything is public by default. Be careful; you can access your enum type and values from outside your struct or your class only if the enum is in a public scope, as any field or function.

这篇关于C vs C ++中的枚举范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆