I have a class method that needs to know the value of a variable named mode
which takes the values 1 an 0 and is a private attribute of the class. I want to write a setter function that can change mode
to 1 or 0. However, I must use an enum to determine the new value that I should set mode
to: enum sequence {error=0,active =1};
I want sequence to be an attribute (I was hoping to make it private) of the class. How can I write a setter function that takes as input active
or error
and sets the value of mode accordingly. Here is the basic structure of my code:
#include <iostream>
class Blink{
public:
void setter(...){
}
private:()
int mode = 0;
enum sequence {error = 0, active = 1};
};
Blink b;
int main() {
b.setter(active);
}
PS: I'm having a hard time coming up with a good title for this question, suggestions are appreciated!
CodePudding user response:
It's pretty straight forward. This is how I would do it in C 11 and above:
class Blink {
public:
enum class Sequence { Error, Active };
void setter(Sequence s) {
if (s == Sequence::Active) {
mode = 1;
} else {
mode = 0;
}
}
private:
int mode = 0;
};
Blink b;
int main() {
b.setter(Blink::Sequence::Active);
}
The main difference is that Sequence
is declared publicly. Note that mode
is still a private variable so there is no harm. Sequence becomes part of the public interface because it needs to be understood from outside.
The second change is that I use enum class
. Yes, you could also use a plain enum that implicitely casts to the integer, but see Why is enum class preferred over plain enum?
In this simple example, I would instead use private member Sequence mode = Sequence::Error;
instead of int mode = 0;
.