tstrickler
tstrickler

Reputation: 23

Why am I getting a "not declared in scope" error in the declaration itself?

I'm trying to overload the << operator for cout and my custom linked list class. However, I'm getting the error "ptr was not declared in this scope" on the line of the actual declaration itself in the very last method in LinkedList.hpp (LinkedList<T>::Node* ptr = list.getHead();). Am I missing something?

Here's the code:

// LinkedList.hpp

#ifndef LINKED_LIST_HPP
#define LINKED_LIST_HPP

#include <stdexcept>
#include <iostream>

template <typename T>
class LinkedList {
    public:
        class Node {
            private:
                T _data;
                Node* _next;
            public:
                Node(T data);
                T getData();
                Node* getNext();
        };
        LinkedList();
        ~LinkedList();
        int size();
        LinkedList<T>::Node* getHead();
    private:
        LinkedList<T>::Node* _head;
        int _size;
};

template <typename T>
std::ostream& operator<<(std::ostream& strm, LinkedList<T>& list);

#include "LinkedList.cpp"
#endif



// LinkedList.cpp

template <typename T>
LinkedList<T>::Node::Node(T data) {
    _data = data;
    _next = nullptr;
}

template <typename T>
T LinkedList<T>::Node::getData() {
    return _data;
}

template <typename T>
typename LinkedList<T>::Node* LinkedList<T>::Node::getNext() {
    return _next;
}

template <typename T>
LinkedList<T>::LinkedList() {
    _head = nullptr;
    _tail = nullptr;
    _size = 0;
}

template <typename T>
LinkedList<T>::~LinkedList() {
    Node* ptr = _head;
    while (ptr != nullptr) {
        _head = _head->getNext();
        delete ptr;
        ptr = _head;
    }
}

template <typename T>
int LinkedList<T>::size() {
    return _size;
}

template <typename T>
typename LinkedList<T>::Node* LinkedList<T>::getHead() {
    return _head;
}

template <typename T>
std::ostream& operator<<(std::ostream& o, LinkedList<T>& list) {
    if (list.size() == 0) {
        o << "NULL";
    }
    else {
        LinkedList<T>::Node* ptr = list.getHead();
        while (ptr->getNext() != nullptr) {
            o << ptr->getData() << " -> ";
        }
        o << ptr->getData();
    }
    return o;
}

Upvotes: 1

Views: 499

Answers (1)

user975989
user975989

Reputation: 2648

This seems like an issue that Node is a dependent type, and so you need to do this:

typename LinkedList<T>::Node* ptr = list.getHead();

See this answer for more details on when this is necessary and why: Where and why do I have to put the "template" and "typename" keywords?

Upvotes: 1

Related Questions