【发布时间】:2017-12-28 22:46:50
【问题描述】:
这是我尝试过的,但我发现重载只会增加变量,如果我将它分配给另一个变量。即,我进行增量的变量的值不会增加。因此,在下面的示例中,变量 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;
}
【问题讨论】:
-
你为什么期望
static_cast<int>(d) + 1) % 7增加一些东西,以及它是什么东西? -
typedef enum days {...} days;是一种冗余练习。只需定义enum days {...};。 C++ 不需要像 C 一样的杂技来将枚举作为一种类型引入。 -
考虑使用scoped enum。
标签: c++ enums operator-overloading pre-increment