Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ operator overload in an enum class

So I'm writing a game using c++ and in my tutorial state, I have different steps that the user goes through, explaining how the game works. I want to increment which step the user is on after a certain action is performed. (Mouse click). I tried overloading the ++ operator but I get an error saying binary '++': 'STEPS' does not define this operator or a conversion to a type acceptable to the predefined operator. I'm using visual studio and it's error code C2676.

I have my enum class set up as follows:

enum class STEPS
{
    ONE,
    TWO,
    END_OF_LIST
};

STEPS& operator++(STEPS& s)
{
    s = staic_cast<STEPS>(static_cast<int>(s) + 1);
    if (s == STEPS::END_OF_LIST)
    {
        s = static_cast<STEPS>(static_cast<int>(s) - 1);
    }
    return s;
}

In my updating function of my tutorial state class I check if the mouse was clicked. If it was I'm trying to increment steps.

// this is defined in the header and set to STEPS::ONE upon initialization STEPS steps;

TutorialState::Update()
{
    // If mouse was clicked
    if (mouse.Left())
    {
        steps++; // this is giving me an error.
    }
}
like image 825
Vince Avatar asked Dec 06 '22 13:12

Vince


1 Answers

STEPS& operator++(STEPS& s);

is for ++step.

for step++, you need

STEPS operator++(STEPS& s, int) { auto res = s; ++s; return res; }

It has been chosen to use extra parameter int to distinguish between pre and post increment operator.

You may read http://en.cppreference.com/w/cpp/language/operator_incdec for more details.

like image 143
Jarod42 Avatar answered Dec 30 '22 14:12

Jarod42