Pointer list c++
Solution 1
You want
(*it)->printHello();
as the *it
returns the stored pointer A*
and only then you can apply ->
.
Solution 2
Just change following line
it->printHello();
to
(*it)->printHello();
The operator*() gives access to the contained data of the container, which in your case is a pointer. When not using pointers in containers, just using operator->() would work, too.
Solution 3
Let me expand on Daniel's answer.
When you stick an asterisk in front of a variable, it is called 'dereferencing'. Used this way, the Asterisk is a 'Dereference Operator'. To put it noob-ishly (I don't know what level of understanding you have offhand), *pMyPointer
acts like it was the Object that the pMyPointer was pointing to. If it was a Pointer to a Pointer, then the result is just the Pointer.
As an example, when you call a method on a pointer, you use the Into Operator ->
.
These two often do the same thing:
pMyPointer->MyFunction();
(*pMyPointer).MyFunction();
In the case of the C++ iterators, the Dereference Operator is overwritten to return the object stored in its position. In this case, what is stored in its position is a pointer, so you still have to use ->
unless you stick another Dereference Operator in there.
Solution 4
De-referencing it
will give you pointer to A, then you need to access the methods or data members.
So use :
(*it)->printHello();
user1519221
Updated on September 28, 2020Comments
-
user1519221 over 3 years
The code below:
#include <iostream> #include <list> class A { public: void printHello(){std::cout << "hello";} }; int main(int argc, char *argv) { std::list<A*> lista; lista.push_back(new A()); for(std::list<A*>::iterator it=lista.begin();it!=lista.end();++it) { //how to get to printHello method? //it doesn't work it->printHello(); } return 0; }
This code doesn't work. My question is how to get to method 'printHello' by iterator it? Thanks.