Вопрос

I have two classes which inherit from a third class, and they are stored in a list.

I'm trying to iterate that list and call the implemented function of each class, however, the code doesn't compile.

Here is my code:

class A
{   
   public:

   virtual void foo ()=0;
};

class B :public class A
{
   public:

   void foo();
}

class C :public class A
{
   public:

   void foo();
}

std::list<A*> listOfClasses;

listOfClasses.push_back (new B());
listOfClasses.push_back (new C());

for(std::list<A*>::iterator listIter = listOfClasses.begin(); listIter != listOfClasses.end(); listIter++)
{
    listIter->foo()
}

This code doesn't compile, I'm getting the following error message (for the line listIter->foo()):

'foo' : is not a member of 'std::_List_iterator<_Mylist>'

Any ideas why?

Это было полезно?

Решение 4

Your container holds pointers, so you need to de-reference them:

(*listIter)->foo();

Другие советы

You have to use the iterator this way: (*listIter)->foo()

You need to dereference the iterator first:

(*listIter)->foo()

For some variety, here's a simpler alternative syntax for C++11, that avoids this issue altogether:

for (auto p : listOfClasses)
{
    p->foo();
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top