C++ 中的节点继承

Inheritance with Nodes in C++

我正在用 C++ 编写双向链表,并且有一个 class Node 用于单向链表。下面显示了 class.

的定义

Node.h

#ifndef NODE_H
#define NODE_H

template <class T>
class Node {
    public:
        Node<T>() { next = nullptr; } 
        Node<T>(T init) { data = init; next = nullptr; }

        void setData(T newData) { data = newData; }
        void setNext(Node<T> *nextNode) { next = nextNode; }

        const T getData() { return data; }
        Node<T> *getNext() { return next; }
    private:
        T data;
        Node<T> *next;
};

#endif

显然,单向链表和双向链表的主要区别在于指向前一个 Node 的指针,所以我试图从 Node class 继承所有内容在一个新的 class 中并简单地添加一个 prev 属性:

DoublyLinkedList.h

#ifndef DOUBLY_LINKEDLIST_H
#define DOUBLY_LINKEDLIST_H

#include "Node.h"

template <class T>
class DLLNode : public Node {
    public:
        // Inherit default constructor from Node and set prev to nullptr;
        DLLNode<T>() : Node<T>(), prev() {}
        // Inherit constructor from Node and set prev to nullptr;
        DLLNode<T>(T init) : Node<T>(init), prev() {}

        Node<T> *getPrev() { return prev; }
    private:
        Node<T> *prev;
};

/*
    TODO: Implement doubly linked list class
*/

#endif

我的驱动程序如下:

driver.cc

#include <iostream>
#include "DoublyLinkedList.h"

int main() 
{
    DLLNode<int> test;

    return 0;
}

编译时出现以下错误:

./DoublyLinkedList.h:7:24: error: expected class name
class DLLNode : public Node {
                       ^
./DoublyLinkedList.h:9:18: error: type 'Node<int>' is not a direct or virtual base of 'DLLNode<int>'
                DLLNode<T>() : Node<T>(), prev() {}
                               ^~~~~~~
driver.cc:6:15: note: in instantiation of member function 'DLLNode<int>::DLLNode' requested here
        DLLNode<int> test;

我不明白为什么 class Node 没有被识别为 class,正如我的编译器在第一个错误中所声称的那样。任何提示将非常感谢。

我的编译器是Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)

您需要将模板类型参数传递给您的模板基class,继承时:

template <typename T>
class DLLNode : public Node<T> {
                        // ^^^
   // ...
};