C 枚举类可以使用方法
Can a C++ enum class have methods?
我有一个带有两个值的枚举类,我想创建一个接收值的方法并返回另一个。我还想保持类型的安全性(这就是为什么我使用枚举类代替枚举)。
http://www.cplusplus.com/doc/tutorial/other_data_types/没有提及有关方法的任何信息但是,我的印象是任何类型的类都可以使用方法。
虽然答案"你不能"从技术上讲是正确的,我相信您可能能够实现您想要使用以下想法的行为:
我想你想写的东西:
Fruit f = Fruit::Strawberry;
f.IsYellow();
您希望代码看起来像这样:
enum class Fruit : uint8_t
{
Apple,
Pear,
Banana,
Strawberry,
bool IsYellow() { return this == Banana; }
};
但是,当然,它不起作用,因为枚举无法使用方法('this'在上下文中并不意味着任何方法)
但是,如果您使用包含非类枚举和包含该类型值的单个成员变量的普通类的想法,则可以非常接近所需的语法/行为/类型的安全性。即:
class Fruit
{
public:
enum Value : uint8_t
{
Apple,
Pear,
Banana,
Strawberry
};
Fruit() = default;
constexpr Fruit(Value aFruit) : value(aFruit) { }
#if Enable switch(fruit) use case:
// Allow switch and comparisons.
constexpr operator Value() const { return value; }
// Prevent usage: if(fruit)
explicit operator bool() const = delete;
#else
constexpr bool operator==(Fruit a) const { return value == a.value; }
constexpr bool operator!=(Fruit a) const { return value != a.value; }
#endif
constexpr bool IsYellow() const { return value == Banana; }
private:
Value value;
};
现在您可以写:
Fruit f = Fruit::Strawberry;
f.IsYellow();
编译器将防止诸如:
之类的事情Fruit f = 1; // Compile time error.
您可以轻松添加方法:
Fruit f("Apple");
和
f.ToString();
可以支持。
不,他们不能。
我可以理解,在C 11中强键入枚举的enum class
部分似乎也暗示您的enum
也具有class
特征,但事实并非如此。我有根据的猜测是,关键字的选择是灵感来自我们在C 11之前使用的模式来获得范围的枚举:
class Foo {
public:
enum {BAR, BAZ};
};
但是,这只是语法。同样,enum class
不是class
。
专注于问题的描述,而不是标题,可能的答案是
struct LowLevelMouseEvent {
enum Enum {
mouse_event_uninitialized = -2000000000, // generate crash if try to use it uninitialized.
mouse_event_unknown = 0,
mouse_event_unimplemented,
mouse_event_unnecessary,
mouse_event_move,
mouse_event_left_down,
mouse_event_left_up,
mouse_event_right_down,
mouse_event_right_up,
mouse_event_middle_down,
mouse_event_middle_up,
mouse_event_wheel
};
static const char* ToStr (const type::LowLevelMouseEvent::Enum& event)
{
switch (event) {
case mouse_event_unknown: return "unknown";
case mouse_event_unimplemented: return "unimplemented";
case mouse_event_unnecessary: return "unnecessary";
case mouse_event_move: return "move";
case mouse_event_left_down: return "left down";
case mouse_event_left_up: return "left up";
case mouse_event_right_down: return "right down";
case mouse_event_right_up: return "right up";
case mouse_event_middle_down: return "middle down";
case mouse_event_middle_up: return "middle up";
case mouse_event_wheel: return "wheel";
default:
Assert (false);
break;
}
return "";
}
};
有一个非常兼容的能力(§)将枚举重新分配到类中而无需重写您的代码,这意味着有效地您可以做您要做的事情,而无需太多编辑。
(§)正如ElementW在注释中指出的那样, type_traits 依赖代码将无法工作,因此例如。一个人不能使用自动等。可能有某种方法来处理此类内容,但最终将枚举转换为一类,颠覆C
始终是一个错误 enum struct
和enum class
规格是关于范围的,因此不是其中的一部分。
您的原始枚举是例如'宠物'(这是一个例子!)。
enum pet {
fish, cat, dog, bird, rabbit, other
};
(1)您将其修改为Petenum(以将其隐藏在现有代码中)。
enum petEnum {
fish, cat, dog, bird, rabbit, other
};
(2)您在其下方添加一个新类声明(用原始枚举命名)
class pet {
private:
petEnum value;
pet() {}
public:
pet(const petEnum& v) : value{v} {} //not explicit here.
operator petEnum() const { return value; }
pet& operator=(petEnum v) { value = v; return *this;}
bool operator==(const petEnum v) const { return value == v; }
bool operator!=(const petEnum v) const { return value != v; }
// operator std::string() const;
};
(3)现在,您可以在宠物课上添加任何喜欢的课程方法。 例如。字符串操作员
pet::operator std::string() const {
switch (value) {
case fish: return "fish";
case cat: return "cat";
case dog: return "dog";
case bird: return "bird";
case rabbit: return "rabbit";
case other: return "Wow. How exotic of you!";
}
}
现在您可以使用EG STD :: Cout ...
int main() {
pet myPet = rabbit;
if(myPet != fish) {
cout << "No splashing! ";
}
std::cout << "I have a " << std::string(myPet) << std::endl;
return 0;
}
,如其他答案中所述,否。即使是enum class
也不是类。
通常需要需要具有enum
的方法是由于它不是 juromand (只是增加)枚举的原因,而是对值的位定义。掩盖或需要其他位算术操作:
enum class Flags : unsigned char {
Flag1 = 0x01 , // Bit #0
Flag2 = 0x02 , // Bit #1
Flag3 = 0x04 , // Bit #3
// aso ...
}
// Sets both lower bits
unsigned char flags = (unsigned char)(Flags::Flag1 | Flags::Flag2);
// Set Flag3
flags |= Flags::Flag3;
// Reset Flag2
flags &= ~Flags::Flag2;
显然,人们认为将必要的操作封装以重新/设置单个/组的位,例如位蒙版值甚至位索引驱动的操作将对操纵这样的"标志"很有用。
C 11 struct
/class
规范仅支持更好地范围来访问访问值。没有更多,也没有!
摆脱您的限制方法无法声明枚举(类)>的方法,是使用std::bitset
(包装程序类)或Bitfield union
。
union
s和这样的比特菲尔德工会 can 有方法(有关限制,请参见此处!)。
我有一个示例,如何将位掩码值(如上所述)转换为其相应的位索引,可以在此处沿std::bitset
使用:bitindexexconverter.hpp
我发现这对于增强基于"标志"的算法的可读性非常有用。
它可能无法满足您的所有需求,但是对于非成员操作员,您仍然可以很有趣。例如:
#include <iostream>
enum class security_level
{
none, low, medium, high
};
static bool operator!(security_level s) { return s == security_level::none; }
static security_level& operator++(security_level& s)
{
switch(s)
{
case security_level::none: s = security_level::low; break;
case security_level::low: s = security_level::medium; break;
case security_level::medium: s = security_level::high; break;
case security_level::high: break;
}
return s;
}
static std::ostream & operator<<(std::ostream &o, security_level s)
{
switch(s)
{
case security_level::none: return o << "none";
case security_level::low: return o << "low";
case security_level::medium: return o << "medium";
case security_level::high: return o << "high";
}
}
这允许
之类的代码security_level l = security_level::none;
if(!!l) { std::cout << "has a security level: " << l << std::endl; } // not reached
++++l;
if(!!l) { std::cout << "has a security level: " << l << std::endl; } // reached: "medium"
基于JTLIM的答案
ifea(解决方案)
enum ErrorType: int {
noConnection,
noMemory
};
class Error {
public:
Error() = default;
constexpr Error(ErrorType type) : type(type) { }
operator ErrorType() const { return type; }
constexpr bool operator == (Error error) const { return type == error.type; }
constexpr bool operator != (Error error) const { return type != error.type; }
constexpr bool operator == (ErrorType errorType) const { return type == errorType; }
constexpr bool operator != (ErrorType errorType) const { return type != errorType; }
String description() {
switch (type) {
case noConnection: return "no connection";
case noMemory: return "no memory";
default: return "undefined error";
}
}
private:
ErrorType type;
};
用法
Error err = Error(noConnection);
err = noMemory;
print("1 " + err.description());
switch (err) {
case noConnection:
print("2 bad connection");
break;
case noMemory:
print("2 disk is full");
break;
default:
print("2 oops");
break;
}
if (err == noMemory) { print("3 Errors match"); }
if (err != noConnection) { print("4 Errors don't match"); }
是的,他们可以,但是您需要做一个包装类别,例如:
#include <iostream>
using namespace std;
class Selection {
public:
enum SelectionEnum {
yes,
maybe,
iDontKnow,
canYouRepeatTheQuestion
};
Selection(SelectionEnum selection){value=selection;};
string toString() {
string selectionToString[4]={
"Yes",
"Maybe",
"I don't know",
"Can you repeat the question?"
};
return selectionToString[value];
};
private:
SelectionEnum value;
};
int main(){
Selection s=Selection(Selection::yes);
cout<<s.toString()<<endl;
return 0;
}
- 如何公开库的枚举,以便我的代码不必键入整个命名空间来使用该枚举?
- 在编译时使用 和枚举作为索引分配数组的值 (C++)
- 安全使用严格枚举 C++ 11
- 表达式中使用的枚举器是否与其枚举的基础类型具有相同的类型?
- 如何在Qt.js文件中使用C++枚举
- 使用 DFS 枚举子集
- 在 QML 中使用 c++ 枚举作为字符串
- 使用 Doxygen 或类似方法记录枚举标志
- 如何使用 SWIG 枚举枚举成员
- C 枚举类可以使用方法
- 有没有一种方法可以在枚举中使用关键字作为标识符
- C++使用模板为特定的枚举值创建方法
- 如何在 C++11 中“使用”弱枚举
- 如何在 c++ 中的 Normal 或 Singleton 类中 GoogleTest 私有方法/枚举类
- 在哪些情况下应使用匿名枚举
- 使用结构枚举作为参数的 C++ 无法编译
- 使用方向枚举列表时反转方向(从左到右或从上到下)
- 在lldb中使用匿名枚举作为函数参数错误
- 在使用特定枚举标识符时打印出静态"deprecate"警告消息并附上建议的更正?
- 使用带有枚举的字符串