C ++枚举类可以有方法吗?

C ++枚举类可以有方法吗?

问题描述:

我有一个带有两个值的枚举类,并且我想创建一个接收值的方法 并返回另一个.我还想保持类型安全(这就是为什么我使用enum类而不是enums的原因).

I have an enum class with two values, and I want to create a method which receives a value and returns the other one. I also want to maintain type safety(that's why I use enum class instead of enums).

http://www.cplusplus.com/doc/tutorial/other_data_types/没有提及任何方法 但是,我给人的印象是任何类型的类都可以有方法.

http://www.cplusplus.com/doc/tutorial/other_data_types/ doesn't mention anything about methods However, I was under the impression that any type of class can have methods.

不,他们不能.

我可以理解,C ++ 11中强类型枚举的enum class部分似乎暗示您的enum也具有class特征,但事实并非如此.我的有根据的猜测是,关键字的选择受到了我们在C ++ 11之前用来获取范围枚举的模式的启发:

I can understand that the enum class part for strongly typed enums in C++11 might seem to imply that your enum has class traits too, but it's not the case. My educated guess is that the choice of the keywords was inspired by the pattern we used before C++11 to get scoped enums:

class Foo {
public:
  enum {BAR, BAZ};
};

但是,这只是语法.同样,enum class不是class.

However, that's just syntax. Again, enum class is not a class.