'Overloading ostream << operator for a class with private key member
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?
Solution 1:[1]
Declare the function signature inside the class and mark it as friend, then define it outside the class if you want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Haroun D Menai |
