Reputation: 57
I'm looking for an easiest way to print a private Linked List that is inside a class. (In reverse order)
My method is to call a function of the class that plugs the Head as a parameter and the return is another function that performs the task.
I did this because previously I had to get the Head through a Getter function and then plug it in the function call. All this outside of the class.
void Arreglo::InfoDealer(ofstream &salida)
{
return InfoDealer_f(Head, salida);
}
void Arreglo::InfoDealer_f(NodePTR Ptr, ofstream &salida)
{
if (Ptr == NULL)
return;
InfoDealer_f(Ptr->Next, salida);
//output stuff
}
Is this correct? Is there a better way to do this? Thank You. I'm new in CS, so please have patience.
Upvotes: 0
Views: 168
Reputation: 45704
Well, you generally have the right idea and your example should work in the end.
Still, some points to consider:
Use a public friend function of the stream-inserter variety for better idiomatic use:
inline ostream& operator<<(ostream& o, const myclass& m) {
m.print_helper(m._head, o);
return o;
}
// Add in class:
friend ostream& operator<<(ostream& o, const myclass& m);
NodePTR
should be Node*
.Upvotes: 1
Reputation: 9648
I don't quite understand your example, but yes, you generally have a public method (the interface) and a private helper method:
class my_class
{
public:
void print( ostream& out );
private:
NodePtr _head;
void print_helper( NodePtr node, ostream& out );
}
void my_class::print( ostream& out ){ print_helper( _head, out ); }
Upvotes: 1