I have a base classe called StateDefinition and it has the following definition:
class StateDefinition
{
public:
StateDefinition();
virtual bool condition() { return false; }
virtual void reach() {}
};
I have some derivated classes that override the condition and reach methods. I use a std::vector<StateDefinition*> m_stateMachine
to store objects from the derivated classes. Then I am trying to access the elements as following:
for (auto state = m_stateMachine.begin(); state != m_stateMachine.end(); state++)
{
if (!state->condition())
{
state->reach();
break;
}
}
But this code it is not compiling, I am gettig the following error:
error: member reference base type 'std::_Simple_types::value_type' (aka 'StateDefinitions *') is not a structure or union
So my question is: How to access elements of a polymorphic vector with a for?
state is an iterator and you use a vector of pointer, so you need to dereference one more time
for (auto state = m_stateMachine.begin(); state != m_stateMachine.end(); state++)
{
if (!(*state)->condition())
{
(*state)->reach();
break;
}
}
Else an easier way is :
for (auto state : m_stateMachine) {
if (!state->condition())
{
state->reach();
break;
}
}
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.