Overloading the insert operator

I'm really not sure how to call the function:

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

      

which 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);
};

      

+2


source to share


3 answers


This is no different than using the flow operator <<for any other type (this is called operator overloading for whatever reason).

However, the output shouldn't modify the object, so you really need to pass it by const reference (otherwise calls with temporary data won't compile).



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

      

+3


source


This operator is a classic binary operator.

// Say I have an operator declared like this:
return_type operator@(left_type lhs, right_type rhs);

// Then the invocation is done this way:
left_type L;
right_type R;
return_type result = L @ R;

      

In the case of the stream operator, this is a bit special, since the left-hand argument and return type are actually the same type (and indeed, will refer to the same object, albeit at different times). This is to ensure the chain.

// Chaining
std::cout << "<Output>  " << 1 << std::endl;

// Which can be analyzed like such
operator<<(
  operator<<(
    operator<<(
      std::cout ,
      "<Output>  "
    ),
    1
  ),
  std::endl
);

      



As you can see, the syntax just allows a convenient call. You can see that the order is very well defined, it is strictly left to right.

So with your object it would be:

stack s;
std::cout << s << std::endl;

      

Just!

+3


source


Call him from where? Since it is only encoded by the class, it is aware of the private structure. No code external to the class can use this method because it cannot instantiate the structure. Marking this as a friend is not good.

+1


source







All Articles