I am making a class and I want to create an enum inside that class so that it can only be accessed through the namespace of that class. I would want users to be able to access the enum outside of the class like so:
GpioPin pin(23, GpioPin::OUTPUT);
where GpioPin is the class and OUTPUT is one of the enum values.
I tried putting the enum at the top of the class and I tried putting it under the public label like (constructor included for help debugging):
public:
enum pin_dir {
INPUT,
OUTPUT,
};
GpioPin(int pin_num, pin_dir dir): pin_num(pin_num), dir(dir) {
std::string dir_str;
if(dir == INPUT){
dir_str = "in";
} else if (dir == OUTPUT){
dir_str = "out";
} else {
std::cout << "invalid direction in constructor for pin " << pin_num << std::endl;
return;
}
init_gpio_pin(pin_num, dir_str.c_str());
}
but when under the public tag the constructor acts like the enum doesn't exist and throws a compiler error.
Does anyone know the proper way to do this?
Thanks
Edit: the problem has been solved. The code that is depicted here is correct and works as intended. The accepted answer gives some good information about enum class in C++
Look at enum class (google for c++ enum class).
Class Foo {
public:
enum class Color{ Red, Green, Blue};
};
Then, you reference things as:
Foo::Color::Red
Works great.