复制和分配构造函数的问题

问题描述 投票:0回答:1

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

// 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);
    }

我该怎么办?

c++ deep-copy
1个回答
2
投票

基于错误消息,看来您的LinkedList没有可在const对象上调用的begin()end()的变体。但是,复制构造函数和赋值运算符的参数为const。您将必须添加begin()end()的const版本。

© www.soinside.com 2019 - 2024. All rights reserved.