I am getting "error: invalid conversion from ‘int’ to ‘num'" when i compile the below sample code in c++. Typecasting it with enum name doesn't help.
#include <iostream>
using namespace std;
typedef enum
{
NUM_ZERO = 0,
NUM_ONE = 1,
NUM_TWO = 2,
NUM_THREE = 4
} num;
int main()
{
num* numFlag;
*numFlag |= static_cast<num>(NUM_TWO);
return 0;
}
Please let me know if anyone knows how to resolve this.
Syntactically speaking,
*numFlag |= static_cast<num>(NUM_TWO);
is equivalent to
*numFlag = (*numFlag | static_cast<num>(NUM_TWO));
That explains the compiler warning/error. You would need to cast the result of the | operator.
*numFlag = static_cast<num>(*numFlag | NUM_TWO);
To make it work, you should use
int main()
{
// Make numFlag an object instead of a pointer.
// Initialize it.
num numFlag = NUM_ZERO;
// Perform the bitwise |
numFlag = static_cast<num>(numFlag | NUM_TWO);
return 0;
}
If you insist on doing this, at least wrap the ugliness up in an operator, so the rest of the code can be written at least reasonably cleanly:
#include <iostream>
using namespace std;
enum num
{
NUM_ZERO = 0,
NUM_ONE = 1,
NUM_TWO = 2,
NUM_THREE = 4
};
num &operator|=(num &a, num const &b) {
a = static_cast<num>(a | b);
return a;
}
int main()
{
num numFlag;
numFlag |= NUM_TWO;
}
But keep in mind that this will let you generate values that aren't in your enumeration. For example, a sequence like:
num a{NUM_ZERO};
a |= NUM_TWO;
a |= NUM_THREE;
...gives a a value that's not in the enumeration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With