4

I have a few enums in my program and I want to share it across different classes.

When I tried to define it in each class I got a "redefining" error.

Then I searched Google and saw that I should put it in a different header. I tried to to do that and included the header into every class header - I still got the same error.

Searched some more and found in StackOverflow a thread saying I should put them in their own namespace. So I tried:

enum.h:

namespace my_enums
{
enum classification {DATA_STORAGE,DMS,E_COMMERCE,GAMING,RTES,SECURITY};
enum skill { CPP, JAVA, SCRIPT, WEB, SYSTEM, QA };
enum company_policy {CHEAP, LAVISH, COST_EFFECTIVE};
}

But that still doesn't work: First, if tell classes that include the header to: "using namespace my_enums;" I get " is ambiguous" error.

What is the correct way to do what I'm trying to do?

Thanks in advance ^_^

Lost_DM
  • 941
  • 2
  • 10
  • 24

4 Answers4

7

Did you remember the multiple inclusion guard? Normally looks like:

#ifndef MY_HEADER_FILE_H
#define MY_HEADER_FILE_H
[...code...]
#endif

and protects types and enums from getting defined multiply in a compilation unit.

thiton
  • 35,651
  • 4
  • 70
  • 100
5

You only need to declare your enums once in a header if you wish and include that header where you use the enums:

//enum.h:
//include guards:
#ifndef MY_ENUMS
#define MY_ENUMS
namespace my_enums
{
enum classification {DATA_STORAGE,DMS,E_COMMERCE,GAMING,RTES,SECURITY};
enum skill { CPP, JAVA, SCRIPT, WEB, SYSTEM, QA };
enum company_policy {CHEAP, LAVISH, COST_EFFECTIVE};
}
#endif

//A.h

#include "enum.h"
class A
{
   void check()
   {
      my_enums::skill val = my_enums::SCRIPT;
   } 
};
Pubby
  • 51,882
  • 13
  • 139
  • 180
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Maybe you've included it more then once?

Don't forget to add "guards" on include

#ifndef MY_ENUM_H_
#define MY_ENUM_H_

.... enter your enums here ...
#endif // MY_ENUM_H_
Sergei Nikulov
  • 5,029
  • 23
  • 36
0
struct Classification
{
    enum Enum{ dataStorage, dms, eCommerce, gaming, rtes, security }
};

struct Skill
{
    enum Enum{ cpp, java, script, web, system, qa };
};

struct CompanyPolicy
{
    enum Enum{ cheap, lavish, cost_effective };
};

void whatever( Classification::Enum classification ) {}

class A
    : protected Classification
{
public:
    void foo() { whatever( dataStorage ); }
};

class B
{
public:
    void foo() { whatever( Classification::dataStorage ); }
};
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331