PDA

View Full Version : error: invalid conversion from ‘int’ to ‘InitializationState



saman_artorious
12th May 2012, 08:56
I got to add some C code to my qt object n it's important not to change the C code at all.
qt notifies the following error:


error: invalid conversion from ‘int’ to ‘InitializationState’

when the C code tries to OR an element of the enum type with it's variable.

Here's the description:




enum InitializationState {

INIT_NO_ONE = 0x00,
INIT_NO_TWO = 0x01,
INIT_NO_THREE = 0x02,
INIT_NO_FOUR = 0x04
};

typedef enum InitializationState InitializationState_t;

InitializationState_t InitState = INIT_NO_ONE;


the errors I receive pop up one by one whenever I try to OR:


InitState |= INIT_NO_ONE;


I also tried accessing the elements of enum using . sign, though it failed.
any helps would be appreciable : )

mvuori
12th May 2012, 10:20
Casting like this should work:

InitState = static_cast<InitializationState>(InitState | INIT_NO_ONE);

Spitfire
17th May 2012, 16:05
Or just:


InitState = InitializationState(InitState | INIT_NO_ONE);

d_stranz
17th May 2012, 17:48
Or even easier: use QFlags.


typedef enum InitializationState
{

INIT_NO_ONE = 0x00,
INIT_NO_TWO = 0x01,
INIT_NO_THREE = 0x02,
INIT_NO_FOUR = 0x04
};

Q_DECLARE_FLAGS( InitializationStates, InitializationState );
Q_DECLARE_OPERATORS_FOR_FLAGS( InitializationStates );

InitializationStates initState = INIT_NO_ONE; // NOTE: "InitializationStates", not "InitializationState"

initState |= INIT_NO_TWO;

if ( initState.testFlag( INIT_NO_TWO ) )
{
// INIT_NO_TWO is set.
}


Then you can AND, OR, and test bits using the QFlags operators with no need to cast anything.

ChrisW67
18th May 2012, 06:04
The original problem is that an enum variable of type InitializationState can only hold one of the allowable enum values at a time. The compiler is telling you no for a reason. Trying to stuff an illegal value into the variable by using an evil cast is not going to end well.

QFlags is the Qt answer as d_stranz has pointed out.