如何在 C++ 中重载枚举的 ++ 运算符

问题描述 投票:0回答:3

这是我尝试过的,但我发现如果我将变量分配给另一个变量,重载只会增加变量。即,我对其进行增量的变量的值不会增加。因此,在下面的示例中,变量

newDay
为 THU,但
currentDay
仍为 WED。

如何定义重载运算符来增加我正在执行操作的变量?

typedef enum days {MON, TUE, WED, THU, FRI, SAT, SUN} days;

inline days operator++ (days& d) {
    return static_cast<days>((static_cast<int>(d) + 1) % 7);
}

int main(int argc, const char * argv[]) {
   days currentDay = WED;
   days newDay = ++currentDay;
   cout << "Current day: " << currentDay << ", Stored day: " << calendar[0] << ", New day: " << newDay << endl;
}
c++ enums operator-overloading pre-increment
3个回答
4
投票

如果我将你的重载运算符修改为:

inline days operator++ (days const& d) {
    return static_cast<days>((static_cast<int>(d) + 1) % 7);
}

尽管我在那里添加了

const
说明符,但它仍然可以编译。那是因为您 没有像前缀
d
需求的语义那样修改
++

因此,如果您希望操作员达到预期的效果,请务必对其进行修改:

inline days operator++ (days& d) {
    d = static_cast<days>((static_cast<int>(d) + 1) % 7);
    return d;
}

无需评论您自己设计的有效性,请注意,人们普遍认为前缀

operator++
应该返回一个可修改的左值,就像内置函数一样。请记住,如果您发现自己编写了类似
++x = y
的代码,则需要返回引用,即
date& operator++(date&)


0
投票

我之前见过用宏完成此操作

这仅定义前后增量,但您也可以定义按位操作(如果您不想使用

int
并且真的只想使用
enum class

#include <map>
#include <string>
using std::map, std::string;

enum class MouseButton {
  Left,
  Middle,
  Right,

  NUM_BUTTONS
};

#define PRE_AND_POST_INCREMENT( ENUM ) \
  inline ENUM operator++( ENUM& enumVal ) { \
    enumVal = (ENUM)((int)enumVal + 1); \
    return enumVal; \
  } \
\
  inline ENUM operator++( ENUM& enumVal, int postIncrement ) { \
    ENUM oldValue = enumVal; \
    enumVal = (ENUM)((int)enumVal + 1); \
    return oldValue; \
  }
  
PRE_AND_POST_INCREMENT( MouseButton )

map< MouseButton, string > mouseButtonName = {
  { MouseButton::Left, "Left" },
  { MouseButton::Middle, "Middle" },
  { MouseButton::Right, "Right" },
};

int main() {

  for( MouseButton mb = MouseButton::Left; mb < MouseButton::NUM_BUTTONS; mb++ ) {
    puts( mouseButtonName[ mb ].c_str() );
  }
  
}

-1
投票

您定义了后缀运算符。后缀运算符的正常行为是增加其参数的值,但返回原始值。它应该像这样:

days operator++(days& d,int){
    days temp=d;
    d=static_cast<days>((static_cast<int>(d) + 1) % 7);
    return temp;
}

你想要的是前缀运算符。这会增加参数的值并返回对其参数的引用。它应该看起来像这样:

days& operator++(days& d){
    d=static_cast<days>((static_cast<int>(d) + 1) % 7);
    return d;
}
© www.soinside.com 2019 - 2024. All rights reserved.