Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing enums in c++ over classes

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 ^_^

like image 701
Lost_DM Avatar asked Dec 17 '22 07:12

Lost_DM


2 Answers

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.

like image 91
thiton Avatar answered Dec 31 '22 02:12

thiton


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;
   } 
};
like image 27
Luchian Grigore Avatar answered Dec 31 '22 00:12

Luchian Grigore