队列C++的运算符重载
Operator Overloading for Queue C++
我试图使用重载运算符方法将一个队列的条目复制到另一个队列中,但我的函数出错了。我不知道除了下面我所拥有的之外,还有什么其他方式可以访问队列"原始"的值:
struct Node
{
int item;
Node* next;
};
class Queue
{
public:
// Extra code here
void operator = (const Queue &original);
protected:
Node *front, *end;
};
void Queue::operator=(const Queue &original)
{
//THIS IS WHERE IM GOING WRONG
while(original.front->next != NULL) {
front->item = original.front->item;
front->next = new Node;
front = front->next;
original.front = original.front->next;
}
}
你有函数式复制构造函数吗? 如果是这样,我会像这样根据复制构造函数实现你的赋值运算符:
#include <algorithm> // <utility> for C++11
void Queue::operator=(const Queue &other)
{
// Assumes your only field is the "front" pointer.
Queue tmp(other); // May throw.
std::swap(front, tmp.front); // Will not throw.
}
这个想法是,您在将清理资源的临时对象中执行任何可以抛出异常的操作(例如您对operator new()
的调用),然后通过在非抛出操作中交换内容来"提交"您的更改,以便即使在构造tmp
期间抛出异常,您的Queue
状态也是理智的。 指针赋值保证不会抛出,这就是为什么在这种情况下对 std::swap()
的调用是非抛出的。 离开赋值运算符的范围后,tmp
的析构函数应该清理旧的链接列表,因为它的front
与旧front
交换了。
有关此"复制到临时和交换"习惯用法的详细信息,以及它与强异常安全保证的关系,请参阅 GotW #59。
void Queue::operator=(const Queue &original)
{
Node* tmp = original.front;
//THIS IS WHERE IM GOING WRONG
while(tmp->next != NULL) {
front->item = tmp->item;
front->next = new Node;
front = front->next;
tmp = tmp->next;
}
}
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用