简体   繁体   中英

Switching between enum values : C++

This should hopefully be an easy question. I haven't dealt much with enums, so I don't fully understand how they work. In my program I'm trying to store a player's job in an enum. I need the functionality that the job can be changed. I'm trying to use a switch statement, but it isn't changing the player's job.

Code:

// if change is True, change the job. If false, simply return the current value
int GameModeState::changeJob(bool change)
{
    int job = Landman; // Default job is landman
    if (change == true)
    {
        switch(job)
        {
        case Landman:
            return job;
            break;
        case Geologist:
            return job;
            break;
        default:
            job = Landman;
            return job;
            break;
        }
    } 
    else 
    {
        return job;
    }
}

// when the player opens the stat sheet, it should change their job
void GameModeState::_statsheet()
 {
     changeJob(true);
 }

What am I doing wrong to have the jobs change? I'm thinking the problem is in the switch statement.

Your logic is wrong. The switch(job) statement brings you into your case statement. In the

case Landman

You immediately return Landman (because you set job to Landman before executing your switch statement, it will ALWAYS return Landman the way you have it coded), which returns you from this function completely. It never attempts to change job to any OTHER job. Note that your break statements are also never executed, as the return immediately returns you from this function call. You probably want this:

case Landman:
   job = geologist;
   return job;

So on and so forth. Futhermore, you are hard coding the default job case to Landman. You probably want to either pass as a variable, or read out of an object, what the CURRENT value of Job is on the player sheet, and then adjust it based on it's current value.

The switch statement is fine. You've got a bunch of useless break statements, but there not causing problems (except making the code less readable).

This is the problem:

// if change is True, change the job. If false, simply return the current value

job is a local variable, the only effect of setting it is the later return job; statement. Your comment should read:

// if change is true, return the new job. If false, simply return the current value

The new value of job IS returned, but you discard the return value.

Of course, you're always setting job = Landman , which means you always take the same path through the switch . The whole function is equivalent to return Landman; .

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