0

I am trying to overload the ostream << operator for class List

class Node
{
public:
    int data;
    Node *next;
};
class List
{
private:
    Node *head;
public:
    List() : head(NULL) {}
    void insert(int d, int index){ ... }
 ...}

To my humble knowledge (overload ostream functions) must be written outside the class. So, I have done this:

ostream &operator<<(ostream &out, List L)
{
    Node *currNode = L.head;
    while (currNode != NULL)
    {
        out << currNode->data << " ";
        currNode = currNode->next;
    }
    return out;
}

But of course, this doesn't work because the member Node head is private. What are the methods that can be done in this case other than turning Node *head to public?

7mood912
  • 13
  • 3
  • Either use `friend` or provide a public `ostream& put(ostream & os)` member function in your class,. which can be used by the global operator overload. – πάντα ῥεῖ Feb 05 '22 at 10:18
  • You have to add the **friend declaration** `ostream &operator<<(ostream &out, List L);` inside the class. – Jason Feb 05 '22 at 10:25
  • @πάνταῥεῖ I have already tried using `friend` declaration and it worked just fine. But I am interested in your method as well. Could you please elaborate more about it? – 7mood912 Feb 05 '22 at 11:59
  • @7mood912 well, something like `std::ostream& Node::put(std::ostream& os) { Node *currNode = this; while (currNode != NULL) { os << currNode->data << " "; currNode = currNode->next; } return os; }` – πάντα ῥεῖ Feb 05 '22 at 12:04

2 Answers2

1

You can solve this by adding a friend declaration for the overloaded operator<< inside class' definition as shown below:

class List
{
   //add friend declaration
   friend std::ostream& operator<<(std::ostream &out, List L);
   
   //other member here
};
Jason
  • 36,170
  • 5
  • 26
  • 60
1

Declare the function signature inside the class and mark it as friend, then define it outside the class if you want.