c++: enum inside of a class using “enum class”

空扰寡人 提交于 2019-12-06 07:48:40

Assuming you want this to be available outside your class, making the enum public makes sense. As an enum class, you will need the enum name to access the values in addition to the class name:

class Patterns {
public:
    enum class PatternType { ... };
...
};
void makePattern(Patterns::PatternType value) { ... };
makePattern(Patterns::PatternType::bloat);

Because it is an enum class, it may be perfectly valid to move it outside of another class. The only addition to the global namespace will be the name of the enum.

enum class Patterns {
   bloat,
   ...
};
void makePattern(Patterns value) { ... };
makePattern(Patterns::bloat);

If you have other operations you want to group with the enum then nesting it in a class as you have makes sense. You may decide, in that case, to just use enum rather than enum class:

class Patterns {
public:
    enum PatternType { ... };
    std::string toString() const { ... };
    ...
private:
    PatternType value;
};
...
...
void makePattern(Patterns::PatternType value) { ... };
makePattern(Patterns::bloat);

I'd make it public, but otherwise you've done it just as I would.

Your approach is ok, only drawback would be if you are trying to access PatternType from outside the class it would be unreachable since it is declared private.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!