简体   繁体   中英

error C2440: '<function-style-cast>' : cannot convert from 'LinkedList<int>::Node *' to 'LinkedListIterator<const T>'

I am trying to implement linked list iterator and getting compile error. In my test code T is int. When I try to call iterator constructor, it doesn't see the option where Node is passed as an argument.

Here is the code:

template <typename T>
class LinkedListIterator
{
    typedef typename LinkedList<T>::Node Node;
    ...

    LinkedListIterator(Node* p) : p(p) {}
    LinkedListIterator(const LinkedListIterator& other) : p(other.p) {}
    LinkedListIterator& operator=(LinkedListIterator other) { std::swap(p, other.p); return *this; }
    ...
};

template <typename T>
class LinkedList
{
    struct Node ...

    friend class LinkedListIterator<T>;
    friend class LinkedListIterator<const T>;

    ...

    typedef LinkedListIterator<T> iterator;
    typedef LinkedListIterator<const T> const_iterator;

    ...

    const_iterator begin() const //where error happens
    {
        return const_iterator(head->next);
    }
...

};

In your code, you're attempting to construct LinkedList<int>::const_iterator , which is LinkedListIterator<const int> . LinkedListIterator<const int> has two constructors allowing conversions: one copy constructor that I'll ignore, and one from LinkedListIterator<const int>::Node * . LinkedListIterator<const int>::Node * is LinkedList<const int>::Node * . But you don't have a LinkedList<const int>::Node * , you have a LinkedList<int>::Node * . That's a completely different type, so the compiler is right to reject the conversion.

If you want to add any sort of inheritance relation between LinkedList<int> and LinkedList<const int> (I don't know if it makes sense), you could add a partial specialisation and let LinkedList<const T>::Node relate to LinkedList<T>::Node , but without any special work on your part, a compiler error is all you're going to get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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