Typedef enum

typedef enum{
 Adjust_mode_None = 0,
 Adjust_mode_H_min,
 Adjust_mode_H_max,
 Adjust_mode_S_min,
 Adjust_mode_S_max,
 Adjust_mode_V_min,
 Adjust_mode_V_max
}Adjust_mode;

and at some point I want to do:

adjust_mode_ = (adjust_mode_+1)%7; 

but I get the wrong conversion from int to Adjust_mode

This is normal in other languages, what is wrong in C ++? Do I need to define some operator?

+3
source share
2 answers

Yes, you can define an operator ...

Adjust_mode operator+(Adjust_mode lhs, int rhs)
{
    return static_cast<Adjust_mode>(
               (static_cast<int>(lhs) + rhs) % 7);
}

Adjust_mode operator+(int lhs, Adjust_mode rhs)
{
    return static_cast<Adjust_mode>(
               (lhs + static_cast<int>(rhs)) % 7);
}

Note that you need both to let adjust_mode_ + 1 and 1 + adjust_mode_ work. If you provide only one function operator+(Adjust_mode, Adjust_mode), then the above expression instead converts enum to int and returns the result of int.

, , , .

+4

static_cast. .

adjust_mode_ = static_cast<Adjust_mode>(adjust_mode_+1)%7;
+5

Source: https://habr.com/ru/post/1768017/


All Articles