0

In C++ I have:

class linked_list {
public:
    node *head;

    linked_list() : head(nullptr) {}

    bool insert_node(int key) {
        node *new_node = new node(key);
        if (!new_node)
            return false;
        if (!head) {
            head = new_node;
            return true;
        }
        node *ptr = head;
        while (ptr->next) {
            ptr = ptr->next;
        }
        ptr->next = new_node;
        new_node->prev = ptr;
        return true;
    }


    bool delete_node() {
        if (!head)
            return false;
        node *ptr = head;
        while (ptr->next) {
            ptr = ptr->next;
        }
        if (ptr->prev)
            (ptr->prev)->next = nullptr;
        if (!ptr->prev) {
            head = nullptr;
        }
        ptr->prev = nullptr;
        delete ptr;
        return true;
    }

    std::ostream &operator<<(std::ostream &os) {
        node *ptr = this->head;
        while (ptr) {
            os << ptr->key << ',';
            ptr = ptr->next;
        }
        return os;
    }
};

in main function if I write:

linked_list tmp{};
std::cout << tmp << std::endl;

I get the following error message:

error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'linked_list')

why is that?

Please Note: changing the above function to friend will fix this error but yet I don't understand why is that?

Robert
  • 1
  • 1

0 Answers0