c++ - 枚举类型的运算符重载

标签 c++

考虑以下代码:

#include<iostream>


enum week
{
    sun=1,
    mon,
    tue,
    wed,
    thr,
    fri,
    sat
};


week &operator++(week& day,int)
{
    if(day==sat)
        day=sun;
    else
        day++; // This expression
   return day;
}


int main()
{
    week day=sun;
    for(int i=0;i<=10;i++,day++)
    {
        std::cout<<day;
    }
}

在表达式 day++ 中它进入无限递归。

如果我把它像 ((int)day)++编译器给出以下错误:
      error: lvalue required as increment operand

如果我将线路更改为 day=week(((int)day)+1)有用。但是如何修复上面的代码以使其适用于 ++运算符(operator)?

最佳答案

默认的增量运算符不适用于枚举。您必须重载增量运算符(使用 week(((int)day)+1) 逻辑)并在该重载函数中处理环绕。

关于c++ - 枚举类型的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59358549/

相关文章:

c# - 在 C++ 中使用函数名从字符串调用函数

c++ - 需要帮助了解我的 while 循环中发生了什么

c++ - WinAPI : Change Color of a TreeView using CustomDraw

c++ - 如何在 MPI 中发送 std::string?

c++ - 全局设置 stringstream 的精度

c++ - 如何运行代码循环 if (a==b) 并且如果 a != b 没有 "else"则不循环

c++ - 在 QT Creator 中根据 ComboBox 选择修改样式表

c++ - 在 C++ 中读取 pcap 文件

c++ - 从指针到成员的类模板推导

c++ - 错误 : expected primary-expression before ')' token