I should start by saying I'm fairly new to OOP. I am trying to write a portable class which will probably be used in multiple programs. The class requires multiple enumerated lists to store information which are only relevant to the class so I was planning on nesting the enum inside the class. My questions are
Is there any reason to use an enum class
inside a class, or should I just use enum
? Just curious. I posted sample code for reference below.
Is there any reason why it would be a really bad idea to make enums in a class public?
#include <iostream>
enum class Color {
red = 0,
green = 1,
blue = 2
};
class CodeLibray {
public:
enum Color2 {
red = 0,
green = 1,
blue = 2
};
enum class Color3 {
red = 0,
green = 1,
blue = 2
};
Color color;
Color2 color2;
Color3 color3;
};
int main(){
CodeLibray c;
c.color = Color::red;
c.color2 = CodeLibray::Color2::blue;
c.color3 = CodeLibray::Color3::blue;
}
- Is there any reason to use an
enum class
inside a class, or should I just useenum
? Just curious. I posted sample code for reference below.
It's pretty obvious that the enum
values defined inside CodeLibray
would become ambigous if you omit the enum class
there.
- Also, If I want enums to be accessible for assigning public member values but I do not want values in the enum to be changed is this possible?
I don't fully understand what you mean. Just a shot in the dark, something like the following?
enum Color2 {
red = ::red,
// ^^ Refer to the enum declaration in the global namespace
green = ::green,
blue = ::blue
};
enum class Color3 {
red = ::red,
green = ::green,
blue = ::blue
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments