views:

207

answers:

3

I have the following defined:

Stack<ASTNode*>* data;

The way the class is defined, if I do data->push() or data->pop(), I directly push onto the stack or pop off the stack. To get the node at the top of the stack I would do data->peek(). For testing purposes, I would like to print out the top node in the stack like this:

cout << "top of stack is... " << ? << endl;

I'm not sure what the syntax is or how to dereference this.

thanks in advance, Hristo

+7  A: 

It depends on how much information you need. If all you need is the address of the object on the top of the stack (might be enough for debugging, depends what you're doing I guess) the answer is as simple as:

cout << "top of stack is..." << data->peek() << endl;

If you need the object itself, just use:

cout << "top of stack is..." << *(data->peek()) << endl;

or

cout << "top of stack is..." << data->peek()->someIdentifyingMethod() << endl;
Carl Norum
At least if I'm reading his code correctly, that should print out a pointer...
Jerry Coffin
Yeah editing now; the ASTNode* was added to the question since I answered.
Carl Norum
+2  A: 

Assuming your ASTNode class has overloaded operator<<, it looks like you need:

cout << "top of stack: " << *(data->peek()) << endl;
Jerry Coffin
+7  A: 

The syntax you're looking for should be something like this:

cout << "top of stack is... " << *(data->peek()) << endl;

For this to work there needs to be an operator<< defined for ASTNode. If this isn't the case, you can define your own that would look like this:

std::ostream& operator<<(std::ostream &strm, const ASTNode &node) {
  return strm << node.name << ": " << node.value;
}
sth