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

Problems with Copy and assignment constructor

本文关键字:问题 构造函数 赋值 复制      更新时间:2023-10-16

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

// 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:usersrasourcerepossandboxcontaineranotherlinkedlistlinkedlist.h(57): error C2662: 'LinkedList<int>::Iterator LinkedList<int>::begin(void)': cannot convert 'this' pointer from 'const LinkedList<int>' to 'LinkedList<int> &'
1>c:usersrasourcerepossandboxcontaineranotherlinkedlistlinkedlist.h(57): note: Conversion loses qualifiers
1>c:usersrasourcerepossandboxcontaineranotherlinkedlistlinkedlist.h(55): note: while compiling class template member function 'LinkedList<int> &LinkedList<int>::operator =(const LinkedList<int> &)'
1>c:usersrasourcerepossandboxcontaineranotherlinkedlistmain.cpp(20): note: see reference to function template instantiation 'LinkedList<int> &LinkedList<int>::operator =(const LinkedList<int> &)' being compiled
1>c:usersrasourcerepossandboxcontaineranotherlinkedlistmain.cpp(14): note: see reference to class template instantiation 'LinkedList<int>' being compiled
1>c:usersrasourcerepossandboxcontaineranotherlinkedlistlinkedlist.h(57): error C2662: 'LinkedList<int>::Iterator LinkedList<int>::end(void)': cannot convert 'this' pointer from 'const LinkedList<int>' to 'LinkedList<int> &'
1>c:usersrasourcerepossandboxcontaineranotherlinkedlistlinkedlist.h(57): note: Conversion loses qualifiers
1>Done building project "AnotherLinkedList.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

begin和end的迭代器代码如下所示:

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

我做错了什么?

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

大概,你正在寻找这样的东西:

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

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