【发布时间】:2015-04-21 17:55:30
【问题描述】:
我有一个队列的实现,它需要编写一个赋值运算符重载。
Queue& Queue::operator= (const Queue& rhs){
if(this->head == rhs.head) return *this;
Queue * newlist;
if(rhs.head == NULL){
// copying over an empty list will clear it.
this->clear();
return * newlist;
}
newlist = new Queue(rhs);
cout << "made new queue" << endl;
cout << "new list : " << * newlist << endl;
return * newlist;
}
我遇到的问题是,当我离开此功能时,newlist 的内容不再可访问。 operator=() 函数应该是什么样子?
编辑: queue.h:
class Queue : public LinkedList {
protected:
unsigned maxSize;
public:
Queue(unsigned N = -1);
Queue(const Collection& collection, unsigned N = -1);
~Queue();
Queue(const Queue& obj);
Queue& operator= (const Queue& rhs);
friend std::ostream& operator<<(std::ostream& ostream, const Queue &rhs);
bool add(myType element);
myType element();
bool offer(myType element);
myType peek();
myType poll();
myType remove();
};
【问题讨论】:
-
如果没有看到
Queueclass,很难说它应该是什么样子。不过,杰弗里几乎确定了答案。 -
您使用 new/delete 完全错误 - 在您知道如何配对 new/delete 或将删除委托给智能指针之前避免使用它。
-
return * newlist;在rhs.head == NULL时是未定义的行为,因为此时newlist是一个未初始化的指针。 -
我已经包含了 queue.h 但如果没有 linkedlist.h 可能就没有用了。