Reputation: 11536
Given the following minimal example:
foo.hpp:
class foo {
public:
enum bar {
ONE,
TWO,
THREE
};
bar b;
foo ();
};
foo.cpp:
#include "foo.hpp"
foo::foo () : b(ONE) { }
How can I do what I'm trying to do below?
#include "foo.hpp"
int main () {
foo *f = new foo();
/* None of these work:
f->b = TWO;
f->b = foo::bar::TWO;
f->b = bar::TWO;
*/
return 0;
}
I'm leaning toward the conclusion that this is not idiomatic in C++ and I must wrap the enum with the class in an outer namespace, or otherwise reorganize. What are the options and/or best practice?
Upvotes: 0
Views: 363
Reputation: 96241
In C++ prior to C++11 enums (the enum name itself AND the values) are in the scope of the enclosing namespace/class.
So you would access it as: f->b = foo::TWO;
(as seen in the other answer).
However you can utilize nested structs to make enum management a bit easier:
class foo {
public:
struct bar {
enum Type {
ONE,
TWO,
THREE }
};
bar::Type b;
foo ();
};
Now you can qualify the name with your struct helper.
#include "foo.hpp"
int main () {
foo *f = new foo();
f->b = foo::bar::TWO;
return 0;
}
Upvotes: 1
Reputation: 310950
Enumerators are members of class. So you can write either as
f->b = foo::TWO;
or
f->b = f->TWO;
or even as
f->b = foo::bar::TWO;
provided that your compiler supports the C++ 2011 Standard
Upvotes: 0