链表运算符重载问题
linked list operator overloading issue
我试图建立自己的链表类,但= operator overloading.
遇到了问题 据我所知,我们应该在重载赋值运算符时使用 const 参数,比如使用 linked_list<T>& operator=( const linked_list<T>& a)
. 但是,编译器给了我错误,除非我改linked_list<T>&
A。 编译器将停止在 if(this->head==a.front())
,给我错误
11 error C2662: 'linked_list<T>::front' : cannot convert 'this' pointer from 'const linked_list<T>' to 'linked_list<T> &'
以下是详细信息。
#ifndef _LINKED_LIST_H_
#define _LINKED_LIST_H_
template <class T>
struct node
{
T data;
node<T>* next;
};
template <class T>
class linked_list
{
private:
node<T>* head;
public:
linked_list<T>();
linked_list<T>(const linked_list<T>& a);
~linked_list<T>();
linked_list<T>& operator=(const linked_list<T>& a);
bool isEmpty();
int size() const;
void insert_front(T a);
void insert_end(T a);
void erase_end();
void erase_front();
void print() const;
void erase(node<T>* a);
node<T>*& front()
{
node<T>* ptr = new node<T>;
ptr = head;
return ptr;
}
void setFront(node<T>* a);
};
#endif
template <class T>
linked_list<T>& linked_list<T>::operator=(const linked_list<T>& a)
{
if (this->head == a.front()) // the error mentioned happened here. however,
// if no const in the parameter, it would be
// no error
{
return *this;
}
while (head != nullptr) erase_front();
node<T>* copy;
copy = a.front();
while (copy->next != nullptr)
{
insert_end(copy->data);
copy = copy->next;
}
return *this;
}
有人可以帮忙吗?谢谢。
当访问器返回对拥有结构的引用时,通常最好实现两个版本:一个是非常量并返回非常量引用,另一个是常量并返回常量引用。这样,它可以在变异和非变异上下文中使用。 front()
将是一个很好的候选人。
虽然是一个旁注 - 你可能不想在公共linked_list
界面中公开你的node
,特别是对它们的非常量引用。这是那种完全封装在类中的东西。
问题是front()
不是 const 成员函数,您正在尝试在 const 实例上调用它。
相关文章:
- 一个关于在C++中重载布尔运算符的问题
- 在C++中使用重载提取运算符时出现问题
- 重载运算符与添加问题
- 加、乘、除、减复数的问题 C++ - 运算符重载
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 关于重载 -> 运算符中 const 关键字的特定位置的问题
- 基于 SFINAE 的特征实现问题与函数模板重载
- 关于在成员重载中使用 std::move() 的问题
- 字符 * 未从重载运算符或内存管理问题正确返回
- constexpr 运算符重载使用参数的问题
- c++中重载输入运算符的问题
- 在C++中写入 4D 矢量时遇到问题(没有可行的重载"=")
- 我的重载函数有什么问题?
- C++使用模板参数来解决重载问题
- C++ 中重载成员函数的问题
- 我想知道我将如何实现 + 运算符重载.我已经从我上一个问题中计算出 += 运算符重载
- 为什么C++在自定义结构向量时会出现 ostream 重载问题?
- 解决 CRTP 函数重载歧义问题
- C++:创建线程时出现问题;错误 C2672:"std::invoke":找不到匹配的重载函数
- C++重载构造函数问题