有没有一种方法可以为枚举设置运算符=
Is there a way to have an operator= for an enum?
我有一个枚举,但我希望有一个赋值运算符,以便它能够分配一个不是原始枚举的类型。例如
enum class X : int
{
A, B, C, D
}
enum class Y : char
{
A, B, C, D
}
Y& operator=(Y& lhs, X rhs)
{
return Y = static_cast<Y>(X);
}
但我得到了'operator =' must be a non-static member
。没有办法做到这一点吗?
您不能,因为正如错误消息告诉您的那样,operator=
只能是一个非静态成员函数,enum不能有成员。如果您真的希望能够从不同的枚举进行赋值,也许您应该将Y
作为一个类。另一种可能性是编写一个辅助函数来执行赋值。
枚举类是一种可以避免的繁琐结构。只需将一个旧的枚举封装在一个结构中:
#include <iostream>
struct X
{
enum enum_type { A, B, C, D };
typedef int value_type;
value_type value;
X(enum_type value) : value(value) {}
operator enum_type () const { return static_cast<enum_type>(value); }
};
struct Y
{
enum enum_type { A, B, C, D };
typedef char value_type;
value_type value;
Y(enum_type value) : value(value) {}
operator enum_type () const { return static_cast<enum_type>(value); }
Y& operator = (X rhs) {
value = rhs;
return *this;
}
};
int main()
{
X x = X::A;
Y y = Y::B;
std::cout << y << 'n';
y = x;
std::cout << y << 'n';
}
您可以编写转换函数,而不是转换运算符。在任何情况下,这都是更好的形式,因为它在呼叫现场清楚地表达了意图。
enum class X : int
{
A, B, C, D
};
enum class Y : char
{
A, B, C, D
};
Y to_y(X rhs)
{
auto as_int = static_cast<int>(rhs); // allowed
auto as_char = static_cast<char>(as_int); // allowed if the int is known to fit
return static_cast<Y>(as_char); // allowed if the char is known to be the right value
}
int main()
{
auto x = X::C;
auto y = to_y(x);
return 0;
}
相关文章:
- 不带大括号的枚举形式
- C++为类中的枚举项设置值
- C++如何将字符串数组中的一个点设置为枚举变量
- 如何在枚举上设置范围?
- 使用索引设置矢量枚举时的奇怪行为
- C++:如何将枚举元素设置为无限?
- 设置类的枚举成员无效地使用"枚举"
- 是否有C++准则将第一个枚举设置为"safe"默认值?
- 如何将GLM :: VEC3(1.f,0.f,0.f)设置为枚举值
- 在类中获取并设置枚举变量
- 可以将枚举的默认类型设置为无符号字符
- 有没有一种方法可以为枚举设置运算符=
- 使用包含QProcess枚举的QString在QTextBrowser中设置文本
- 获取和设置C++中的枚举
- 不按递增顺序手动取消枚举和设置值
- 如何使用包含不同typedef枚举的派生类模板设置构造函数初始化列表
- cpp文件中设置静态枚举变量的正确方法
- 专用模板根据变量类型返回/设置枚举值
- 当试图添加类构造时,C++未设置枚举类型
- 在相同的命名空间但不同的类中为枚举设置值?C++