简体   繁体   English

在枚举中重新声明变量

[英]Redeclare variable inside enum

In C, If we re-declare variable inside enum , then compiler gives an error that "'i' redeclared as different kind of symbol".It Ok. 在C中,如果我们在enum重新声明变量,那么编译器会给出一个错误“'我'重新声明为不同类型的符号”。好的。

#include <stdio.h>

int i = 10;

struct S 
{ 
    enum 
    {
        i = 20
    }e; 
};

int main()
{
    printf("%d\n", i);
}

But, In C++, If we redeclare variable inside enum, then it's working fine. 但是,在C ++中,如果我们在枚举中重新声明变量,那么它的工作正常。

#include <iostream>
using namespace std;

int i = 10;

struct S 
{ 
    enum 
    {
        i = 20
    }e; 
};

int main()
{
    cout<<i<<endl;
}

I don't understand, Why doesn't C++ compiler gives an error for redeclaration variable? 我不明白,为什么C ++编译器没有给重新声明变量带来错误?

It doesn't give a re-declaration error because the enumerator is introduced into class scope. 它没有给出重新声明错误,因为枚举器被引入类范围。 Recall that a struct and class are mostly interchangeable in C++. 回想一下,结构和类在C ++中大多可以互换。 The scope of S contains the enumerator i . S的范围包含枚举器i

In C however, struct S doesn't define a scope. 但是在C中, struct S没有定义范围。 There are only 4 types of scope in C: function, file, block, and function prototype. C中只有4种类型的范围:函数,文件,块和函数原型。 As such, i is introduced into file scope where the variable i is already defined. 因此, i被引入到已定义变量i文件范围中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM