2014-02-19 27 views
1

我有2个枚举。如何引用共享重复名称的不同枚举值?

typedef enum { 
BLUE = 1, 
RED = 2 
} FavoriteColor; 

typedef enum { 
ORANGE = 1, 
YELLOW = 2, 
RED = 3 
} Color; 

在我的代码我怎么能指从FavoriteColor枚举一个特定的红色,但颜色不枚举?

+2

注意iOS或Mac API中的所有枚举。所有的枚举值都有与枚举相关的名称。所以你想要'FavoriteRed'和'ColorRed',例如。 – rmaddy

+0

我更喜欢使用'NSString'而不是'int'对象的实例。 '@“com.mycompany.myapp.FavoriteColor.RED”',...好吧,你失去了switch()。这是一个劣势? ;-) –

回答

4

你不行。编译器应该警告你。

enum常量位于全局命名空间中。第二个定义是应该产生错误的重定义。

+0

第二个定义不会产生错误,但其中一个会被忽略。 – neo

1

不可能有范围的枚举。一般的解决方法是使用出现在UIKit等大多数库中的前缀。你应该定义枚举这样的:

typedef enum { 
FavoriteColorBlue = 1, 
FavoriteColorRed= 2 
} FavoriteColor; 

typedef enum { 
ColorOrange = 1, 
ColorYellow = 2, 
ColorRed= 3 
} Color; 

其他唯一的办法是描述here使用与静态接入类常量。

0

使用枚举类而不是枚举。然后你可以为不同的枚举使用相同的名字;

// ConsoleApplication3.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

enum class window {large,small}; 
enum class box {large,small}; 




int main() 
{ 
    window mywindow; 
    box mybox; 
    mywindow = window::small; 
    mybox = box::small; 
    if (mywindow == window::small) 
     cout << "mywindow is small" << endl; 
    if (mybox == box::small) 
     cout << "mybox is small" << endl; 
    mybox = box::large; 
    if (mybox != box::small) 
     cout << "mybox is not small" << endl; 
    cout << endl; 

}