Is there an elegant way to share enum between classes?

P

Pierre Couderc

I want to share enum between 2 classes C1 and C2:

class C1
{
public:
enum shut {AAA,BBB, CCC};
shut m_C1;
void set(shut &s) { m_C1=s;}
};

class C2 : public Cother
{
public:
enum shut {AAA,BBB, CCC};
shut m_C2;
};

void main()
{
C1 a;
C2 b;
a.set(AAA);
b.m_C2 = a.m_C1;
}

Is there a more elegant way than the one I have found, but for which I
do not measure the side effects :

class Cenum
{
public:
enum shut {AAA,BBB, CCC};
};

class C1 : public Cenum
{
public:
shut m_C1;
void set(shut &s) { m_C1=s;}
};

class C2 : public Cother, Cenum
{
public:
shut m_C2;
};
 
R

Rolf Magnus

Pierre said:
I want to share enum between 2 classes C1 and C2:

class C1
{
public:
enum shut {AAA,BBB, CCC};
shut m_C1;
void set(shut &s) { m_C1=s;}
};

class C2 : public Cother
{
public:
enum shut {AAA,BBB, CCC};
shut m_C2;
};

void main()
{
C1 a;
C2 b;
a.set(AAA);
b.m_C2 = a.m_C1;
}

Is there a more elegant way than the one I have found, but for which I
do not measure the side effects :

Yes. You don't need to make an enum a class member. Just put it on namespace
scope, and both classes can easily use them.
 
P

Pierre Couderc

Rolf said:
Pierre Couderc wrote:




Yes. You don't need to make an enum a class member. Just put it on namespace
scope, and both classes can easily use them.
,
Thank you, sure I can put it at at a higher scope, but this may conflict
with other declaration at higer level, obliging me to declare :
enum shut { SHUT_OK, SHUT_ERROR, SHUT_AAA, SHUT_BBB...}

My idea is to keep programation simpler or shorter inside these (friend
or not) classes : OK, ERROR, AAA,BBB...
 
A

Arijit

Pierre said:
<snip>
Thank you, sure I can put it at at a higher scope, but this may conflict
with other declaration at higer level, obliging me to declare :
enum shut { SHUT_OK, SHUT_ERROR, SHUT_AAA, SHUT_BBB...}

My idea is to keep programation simpler or shorter inside these (friend
or not) classes : OK, ERROR, AAA,BBB...

Thats why namespaces are there, to avoid such conflicts. Put the class
and enum declarations within a namespace.

-Arijit
 
P

Paavo Helde

I want to share enum between 2 classes C1 and C2:
One option:

namespace shut_t {
enum shut {AAA,BBB, CCC};
}

class C1 {
public:
typedef shut_t::shut shut;
void set(shut &s);
shut m_C1;
// ...
};

class C2 {
public:
typedef shut_t::shut shut;
shut m_C2;
// ...
};

int main() {
C1 a;
C2 b;
a.set(shut_t::AAA);
// or with: using namespace shut_t;
a.set(AAA);

b.m_C2 = a.m_C1;
}

Regards
Paavo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top