tags:

views:

57

answers:

1

Im trying to call the function:

friend ostream& operator<<(ostream& out, stack::myItem& theItem);

that is public to my stack object:

class stack 
{ 
public: 
    stack(int capacity); 
    ~stack(void); 
     void method1(); 
     ... 

 private: 

    struct myItem 
    { 
    int             item; 
}; 

  ... 
public: 
    friend ostream& operator<<(ostream& out, stack& s); 
    friend ostream& operator<<(ostream& out, stack::myItem& theItem); 
};

What I know is that this function below:

ostream& operator<<(ostream& out, stack& s)
{
 if ( s.count == 0 ) // then no elements have been counted.
    out << "\nstack: empty\n\n";
else
        {
        out << "\nstack: ";
        for ( int i = 0; i < s.count; i++ )
        {
   if ( i < s.count-1 )
                     out << s.myItem[i].item << ", ";
                else out << s.myItem[i].item;
        }
        out << "\n\n";
 }
    return out;
}

given the statement: stack s = stack(7); the function above is called whenever i use: cout << s;

How do I call the function below?

ostream& operator<<(ostream& out, stack::myItem& theItem)

 out << theItem.item;
 return out;
}

Because when I try to do the following:

ostream& operator<<(ostream& out, stack& s)
{
if ( s.count == 0 ) // then no elements have been counted.
        out << "\nstack: empty\n\n";
else
        {
        out << s;   
        }
        return out;
}

It results in a crash, because the statement out << s; will be endless.. While debugging the code will never go to the next statement...

+1  A: 

If you are looking to call it on the myItem struct, then:

for ( int i = 0; i < s.count; i++ )
{
    if ( i < s.count-1 )
        out << s.myItem[i] << ", ";
    else out << s.myItem[i];
}

would call it on each struct in the stack.

In the endlessly recursive one, you are just calling it again on the stack, and in the first version, you are calling it on the "item" int within the myItem struct.

(and as a matter of taste, I prefer to keep end condition loops out of for statements like this:)

for ( int i(0), end(s.count-1); i < end; ++i )
{
    out << s.myItem[i] << ", ";
}
out << s.myItem[s.count];
Todd Gardner
could you elaborate further on the for termination conditon?
If you mean the note at the end, the code without the conditional in the loop more clearly states intent; you are printing out elements 0-[end-1] with a comma following, then the final element with a newline
Todd Gardner