简体   繁体   中英

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM