简体   繁体   English

与C ++中的枚举有关的问题。 这是一个已知问题吗?

[英]problem related to enumeration in c++. is that a known issue already?

I have found a problem with enum in C++. 我发现C ++中的枚举有问题。 I wonder if that is a known issue. 我想知道这是否是一个已知问题。

#include <iostream>

/* run this program using the console pauser or add your own getch,
   system("pause") or input loop */

using namespace std;

enum color { red = 8, green = 7, blue };

int main(int argc, char** argv)
{
    color r = red, g = green, b = blue; 

    cout << r << " " << g<< " " << b << " " <<endl;

    switch (b) {
        case red:
            cout << "a bad thing happened" << endl;
            break;

    }

    return 0;
}

running the program you get: 运行您得到的程序:

8 7 8 a bad thing happened 8 7 8一件坏事发生了

Quoting from cppreference.com cppreference.com报价

If the first enumerator does not have an initializer, the associated value is zero. 如果第一个枚举器没有初始化程序,则关联值为零。 For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one. 对于其定义中没有初始化程序的任何其他枚举器,关联的值是前一个枚举器的值加1。

So basically blue is green +1 => 8 which is equal to red (8) 所以基本上蓝色是绿色+1 => 8等于红色(8)

Yes, b is 8, same as r . 是的, b为8,与r相同。 In enums, if you don't specify the exact value for an enumerator, it will be one more than the previous one, 7+1=8 in your case. 在枚举中,如果未指定枚举数的确切值,则它将比前一个大1,在您的情况下为7 + 1 = 8。

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

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