&#39; =&#39; :无法转换为&#39; CircularDoubleDirectedList <int> :: Node *&#39;到节点*&#39;

时间:2015-04-25 18:22:41

标签: c++

我有Node * current,我存储一个指针指向当前位于&#34; top&#34;的清单。当我将新节点设置为当前时,我得到错误:

'=' : cannot convert from 'CircularDoubleDirectedList<int>::Node *' to 'Node *'
while compiling class template member function 'void CircularDoubleDirectedList<int>::addAtCurrent(const T &)' with [ T=int ]

带有//问题注释的三行如果把它们带走就会生成这些错误。

#include "ICircularDoubleDirectedList.h"

template <typename T> class CircularDoubleDirectedList;
class Node;

template <typename T>
class CircularDoubleDirectedList :
    public ICircularDoubleDirectedList<T>{
public:
    //Variables
    Node* current;
    int nrOfElements;
    direction currentDirection;

    //Functions
    CircularDoubleDirectedList();
    ~CircularDoubleDirectedList();
    void addAtCurrent(const T& element) override;

private:
    class Node
    {
    public:
        T data;
        Node* forward;
        Node* backward;

        Node(const T& element);
    };

};
template <typename T>
void CircularDoubleDirectedList<T>::addAtCurrent(const T& element){
    Node* newNode = new Node(element);
    newNode->data = element;
    if (this->nrOfElements == 0){
        newNode->forward = newNode;
        newNode->backward = newNode;
    }
    else{
        this->current->forward = newNode; // Problem
        this->current->forward->backward = newNode; // Problem
    }
    this->current = newNode; //Problem
}

1 个答案:

答案 0 :(得分:3)

当你将Node声明为在课堂之外时

template <typename T> class CircularDoubleDirectedList;
class Node;

这是在全局命名空间中声明类型Node。它是::Node。然后,在您的班级声明中,current接受 类型:

template <typename T>
class CircularDoubleDirectedList 
    : public ICircularDoubleDirectedList<T>
{
public:
    Node* current;   // this is a pointer to ::Node.
};

然后您提供CircularDoubleDirectedList<T>::Node的声明。这 ::Node的类型相同。它也会首先通过名称解析规则进行查找。所以在这里:

template <typename T>
void CircularDoubleDirectedList<T>::addAtCurrent(const T& element){
    Node* newNode = new Node(element); // newNode is a pointer to
                                       // CircularDoubleDirectedList<T>::Node

但是current是指向仍然不完整的类型::Node的指针。因此错误 - 您无意中创建了名为Node两个类型。

如果您要转发声明Node,则必须在 类中执行此操作:

template <typename T>
class CircularDoubleDirectedList 
    : public ICircularDoubleDirectedList<T>
{
    class Node; // NOW it's CircularDoubleDirectedList<T>::Node
};