简体   繁体   中英

Operator overloading for enum increment

I have this enum, and I simply want to increment an object of that enum by one place.

enum Month {
    january = 1,
    february,
    march,
    april,
    may,
    june,
    july,
    august,
    september,
    october,
    november,
    december
};

With the object of my enum, Month m, I simply want to move the object's variable by one position.

Month operator++(Month &m) {
        m = static_cast<Month>(m + 1);
        return m;
    }

With Month &m as the parameter I get error that it needs to take int as an argument. So if I do "(Month &m, int)" it says that it "must take either zero or one arguments." I read that you don't need Month &m if your operator overload is a member function, so I removed it. After that, I get yet another error: "no match for 'operator++' (operand type is 'Month')". Is there something I am missing?

Main code:

class Date {
    int y, d, month_end; // private
    Month m;

    public:
        Date(int yy, Month mm, int dd) 
        : y(yy), d(dd), m(mm) { 
        }

        Month& operator++(Month &m) { 
            m = static_cast<Month>(m + 1);
            return m;
        }

        void add_month() {
            ++m;
        }

In a comment, you said:

Is there something I'm overlooking? http://ideone.com/uOkSk0

Yes. You are defining the function in an unusual place -- inside the definition of Date . It needs to be a non-member function.

using namespace std;

enum Month {
   january = 1,
   february,
   march,
   april,
   may,
   june,
   july,
   august,
   september,
   october,
   november,
   december
};

Month& operator++(Month &m) {
   m = static_cast<Month>(m + 1);
   return m;
}

class Date {
   int y, d;
   Month m;

   public:
   Date(int yy, Month mm, int dd) // constructor
      : y(yy), d(dd), m(mm) { // member initializer
      }


   void add_month() {
      ++m;
   }
};

int main()
{
   Month m = january;
   ++m;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM