错误 C2440:'=':无法从 'Node<ValueType> *' 转换为 'Node<ValueType> *'

error C2440: '=' : cannot convert from 'Node<ValueType> *' to 'Node<ValueType> *'

本文关键字:gt lt Node ValueType 转换 C2440 错误      更新时间:2023-10-16

我正在做一项家庭作业,不允许使用任何STL容器。我的LinkedList实现是用指针链接在一起的节点的集合。我有另一个名为ContinuousList的类,它有一个数据成员LinkedList,其节点包含指向其他各种LinkedList中节点的指针。我试图将一个返回节点指针的函数的返回值分配给一个同时也是节点指针的变量,但它说这是无效的,我不明白为什么我不能这样做。

template <typename ValueType>
struct Node
{
    Node();
    std::string m_key;
    ValueType m_value;
    Node<ValueType>* m_next;
};

链表类:

template <typename ValueType>
class LinkedList
{
public:
    Node<ValueType>* begin()
    {
        return m_head;
    }
private:
    Node<ValueType>* m_head;
};

ContinuousList:

template <typename ValueType>
class ContinuousList
{
public:
    ValueType* iterate(std::string& key)
    {
        m_curr = m_collection.begin(); // Error occurs here
        ...
    }
private:
    LinkedList<Node<ValueType>*> m_collection;
    Node<ValueType>* m_curr;
};

完整错误消息

1>          error C2440: '=' : cannot convert from 'Node<ValueType> *' to 'Node<ValueType> *'
1>          with
1>          [
1>              ValueType=Node<bool> *
1>          ]
1>          and
1>          [
1>              ValueType=bool
1>          ]
1>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>          while compiling class template member function 'bool *ContinuousList<ValueType>::iterate(std::string &)'
1>          with
1>          [
1>              ValueType=bool
1>          ]
1>          see reference to class template instantiation 'ContinuousList<ValueType>' being compiled
1>          with
1>          [
1>              ValueType=bool
1>          ]
    LinkedList<Node<ValueType>*> m_collection;

这个

正在使m_head成为

      Node<Node<ValueType>*>*

这不是你想要的。

    m_curr = m_collection.begin()
    Node<ValueType> = Node<Node<ValueType>*>*

如果

    Node<Node<ValueType>*>* 

是你想要的,使用

m_collection.begin()->m_value;

或使用

    LinkedList<ValueType>, 

并且它将返回节点

虽然我可能真的很累=D

我从GCC得到的错误消息是:

cannot convert ‘Node<Node<int>*>*’ to ‘Node<int>*’ in assignment

这比编译器给出的废话稍微清楚一些。

m_collection包含包裹在节点中的节点。根据你打算用它做什么,也许它应该只是LinkedList<ValueType>,或者任务应该是m_curr = m_collection.begin()->m_value

此外,ContinuousList::iterate几乎可以肯定地通过引用const来接受其论点。

LinkedList定义中,您假设ValueTypeNode参数,但在ContinuousList中,您将Node<ValueType>作为LinkedList模板参数:

template <typename ValueType>
class ContinuousList
{
// (...)
    LinkedList<Node<ValueType>*> m_collection;
    Node<ValueType>* m_curr;
};

所以你的LinkedList实际上看起来像:

template <typename ValueType>
class LinkedList
{
public:
    Node<Node<ValueType> >* begin()
    {
        return m_head;
    }
private:
    Node<Node<ValueType> >* m_head;
};

当你想这样做的时候,这显然是无效的:

/*Node<ValueType>* */ m_curr = /* Node<Node<ValueType> >* */ m_collection.begin();