复制和赋值构造函数的问题
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: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
是迭代常量元素的迭代器类型的一个版本…
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- constexpr构造函数需要常量成员函数时出现问题
- 有关 c++ 构造函数的问题
- 关于复制构造函数的一个棘手问题
- 复制构造函数隐式转换问题
- 构造函数 (C++) 中的 char 指针参数存在问题
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 关于 std::bitset 构造函数的几个问题?
- 构造函数和 G++ 编译配方的问题
- 在 boost::variant 中类 holden 的复制构造函数存在问题
- C++ 关于两个类构造函数的问题
- 在构造函数 c++ 中初始化属性时出现问题
- 空构造函数和值传递问题
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 复制和赋值构造函数的问题
- 变分模板递归构造函数问题
- C++中用户定义的构造函数出现问题
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- C++的抽象类继承和构造函数的问题
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?