regarding error in getting output from cout

88 Views Asked by At

Error:

no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'node')

#include <iostream>

using namespace std;
class Node
{
    int data;
    Node *next;

public:
    Node(int data1)
    {
        data = data1;
        next = nullptr;
    }
};

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    Node *rootNode = new Node(arr[0]);
    cout << rootNode;
    return 0;
}

I'm expecting to get the linked list.

1

There are 1 best solutions below

0
Remy Lebeau On

I'm expecting to get the linked list

Why would you expect that? How do you think operator<< will know how you want your custom Node class to be printed out?

The code you have shown compiles and runs, but the output is simply the memory address of the Node object, not the data value it holds. That is because there is an existing operator<< that prints raw pointers.

For what you want, you have to tell the operator how you want a Node to be printed. You do that by overloading operator<<, eg:

#include <iostream>
using namespace std;

class Node
{
    int data;
    Node *next = nullptr;

public:
    Node(int data1) : data(data1) { }

    friend ostream& operator<<(ostream &os, const Node &node)
    {
        os << node.data;
        return os;
    }
};

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    Node *rootNode = new Node(arr[0]);
    cout << *rootNode;
    delete rootNode;
    return 0;
}

Output:

1

Online Demo

If you want to print a whole list, you are best off wrapping the Node list inside another class, and then overloading operator<< for that class, eg:

#include <iostream>
using namespace std;

class List
{
    struct Node
    {
        int data;
        Node *next = nullptr;

        Node(int data1) : data(data1) { }
    };

    Node *head, *tail;

public:
    List() : head(nullptr), tail(nullptr) { }
    List(const List&) = delete;
    List& operator=(const List&) = delete;

    ~List()
    {
        Node *n = head;
        while (n)
        {
            Node *next = n->next;
            delete n;
            n = next; 
        }
    }

    void push_back(int data)
    {
        Node **n = (tail) ? &(tail->next) : &head;
        *n = new Node(data);
        tail = *n;
    }

    friend ostream& operator<<(ostream &os, const List &list)
    {
        Node *n = list.head;
        if (n)
        {
            os << n->data;
            while (n = n->next)
            {
                os << ',' << n->data;
            }
        }
        return os;
    }
};

int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    List list;
    for(int elem : arr)
        list.push_back(elem);
    cout << list;
    return 0;
}

Output:

1,2,3,4,5,6

Online Demo