复制和赋值构造函数的问题

Problems with Copy and assignment constructor

我有以下代码,用作链表的一部分:

// copy constructor:
LinkedList<T>(const LinkedList<T> &list) 
{
    // make a deep copy
    for (LinkedList<T>::Iterator i = list.begin(); i != list.end(); i++)
    {
        add(*i);
    }
}


// assignment constructor
LinkedList<T>& operator= (const LinkedList<T> &list) 
{
    // make a deep copy
    for (LinkedList<T>::Iterator i = list.begin(); i != list.end(); i++)
    {
        add(*i);
    }
}

但是当我编译时出现以下错误(这是我将它用作赋值构造函数时):

1>------ Build started: Project: AnotherLinkedList, Configuration: Debug Win32 ------
1>main.cpp
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): error C2662: 'LinkedList<int>::Iterator LinkedList<int>::begin(void)': cannot convert 'this' pointer from 'const LinkedList<int>' to 'LinkedList<int> &'
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): note: Conversion loses qualifiers
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(55): note: while compiling class template member function 'LinkedList<int> &LinkedList<int>::operator =(const LinkedList<int> &)'
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\main.cpp(20): note: see reference to function template instantiation 'LinkedList<int> &LinkedList<int>::operator =(const LinkedList<int> &)' being compiled
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\main.cpp(14): note: see reference to class template instantiation 'LinkedList<int>' being compiled
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): error C2662: 'LinkedList<int>::Iterator LinkedList<int>::end(void)': cannot convert 'this' pointer from 'const LinkedList<int>' to 'LinkedList<int> &'
1>c:\users\ra\source\repos\sandbox\container\anotherlinkedlist\linkedlist.h(57): note: Conversion loses qualifiers
1>Done building project "AnotherLinkedList.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

开始和结束的迭代器代码如下所示:

// get root
    Iterator begin()
    {
        return Iterator(sp_Head);
    }

    // get end
    Iterator end()
    {
        return Iterator(nullptr);
    }

我做错了什么?

根据错误消息,您的 LinkedList 似乎没有可以在 const 对象上调用的 begin()end() 的变体。但是,复制构造函数和赋值运算符的参数是常量。您将必须添加 begin()end().

的 const 版本

据推测,您正在寻找这样的东西:

    ConstIterator begin() const { Iterator(sp_Head); }
    Iterator begin() { Iterator(sp_Head); }

    ConstIterator end() const { ConstIterator(nullptr); }
    Iterator end() { Iterator(nullptr); }

其中 ConstIterator 是迭代 const 元素的迭代器类型的一个版本…