Reputation: 2042
I have 2 enums.
typedef enum {
BLUE = 1,
RED = 2
} FavoriteColor;
typedef enum {
ORANGE = 1,
YELLOW = 2,
RED = 3
} Color;
In my code how can I refer to a specific RED from FavoriteColor enum, but not Color enum?
Upvotes: 2
Views: 1023
Reputation: 243
use enum class instead just enum. Then you can use the same names for different enums;
// 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;
}
Upvotes: 0
Reputation: 998
It is not possible to have scoped enumerations. The general way around this is to use prefixes which appear in most libraries like UIKit. You should define your enumerations like this:
typedef enum {
FavoriteColorBlue = 1,
FavoriteColorRed= 2
} FavoriteColor;
typedef enum {
ColorOrange = 1,
ColorYellow = 2,
ColorRed= 3
} Color;
The only other way would be to use a class with static access to constants as described here.
Upvotes: 1
Reputation: 16650
You can't. And the compiler should warn you about that.
enum
constants live in the global namespace. The second definition is a redefinition that should produce an error.
Upvotes: 5