有没有一种方法可以为枚举设置运算符=

Is there a way to have an operator= for an enum?

本文关键字:枚举 设置 运算符 方法 一种 有没有      更新时间:2023-10-16

我有一个枚举,但我希望有一个赋值运算符,以便它能够分配一个不是原始枚举的类型。例如

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;
}