简体   繁体   中英

print elements of std:: list using iterator c++

I'm trying to iterate through a std::list (containing) objects and print some methods but the compiler complaints that 'print': is not a member of 'std::shared_ptr<A>' However if i create an object std::shared_ptr<A> animal(*it); and call animal.print() it will work just fine why is that? below is the function i'm having trouble with (it's also a small portion of my very large program involving lots of polymorphism)

friend std::ostream& operator<<(std::ostream& out, const Hand& _hand) {         

            std::list< std::shared_ptr<A>>::const_iterator it = _hand.hand.begin();    
            std::shared_ptr<A> animal(*it);  
             animal.print(); //workss  
            while (it != _hand.hand.end()) {            
            it->print();   //doesn't work
                ++it;


            }

     return out;}

The list i'm iterating through is of type A (which is abstract) and contain objects of it's derived classes.

(*it) returns a smart pointer reference, so you need to dereference it again.

(**it).print() or (*it)->print()

Or you may find this neater if you want to call several functions in a row: const auto& animal = **it; animal.print(); const auto& animal = **it; animal.print();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM