简体   繁体   English

为什么我在声明本身中收到“未在范围内声明”错误?

[英]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.我正在尝试为 cout 和我的自定义链表类重载 << 运算符。 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(); ).但是,我在 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;
}

This seems like an issue that Node is a dependent type, and so you need to do this:这似乎是Node是依赖类型的问题,因此您需要执行以下操作:

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?有关何时需要以及为什么需要的更多详细信息,请参阅此答案:我必须将“模板”和“类型名”关键字放在哪里以及为什么要放?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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