1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
int main()
{
enum Color
{
RED,
BLUE
};
enum Fruit
{
BANANA,
APPLE
};
Color a = RED;
Fruit b = BANANA;
if (a == b) // The compiler will compare a and b as integers
cout << "a and b are equal" << endl; // and find they are equal!
else
cout << "a and b are not equal" << endl;
return 0;
}
当C + +比较A和B,这是比较他们为整数,这意味着在上面的例子中,一个确实等于B因为他们都默认为整数0。这是绝对没有希望从A和B是从不同的枚举!
C + + 11定义了一个新的概念,枚举类,使两个强类型的枚举和强烈的范围。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
enum class Color
{
RED,
BLUE
};
enum class Fruit
{
BANANA,
APPLE
};
Color a = Color::RED; // note: RED is not accessible any more, we have to use Color::RED
Fruit b = Fruit::BANANA; // note: BANANA is not accessible any more, we have to use Fruit::BANANA
if (a == b) // compile error here, as the compiler doesn't know how to compare different types Color and Fruit
cout << "a and b are equal" << endl;
else
cout << "a and b are not equal" << endl;
return 0;
}