本文介绍了当使用赋值运算符重载时,新对象不能在operator =()之外访问,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个队列的实现,需要写一个赋值运算符重载。
I have an implementation of a Queue which requires writing an assignment operator overload.
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;
}
我遇到的问题是,当我离开此函数时, 新列表
的内容不再可访问。
The problem I'm running into is that when I leave this function, the contents of newlist
are no longer accessible. How is an operator=() function supposed to look?
编辑:
queue.h:
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();
};
推荐答案
> operator = 应该使用 rhs $ c $的值修改内部对象
(* this)
c>,然后逐字返回(* this)
。
An operator=
is supposed to modify the internal object (*this)
with the values of rhs
and then literally return (*this)
.
这篇关于当使用赋值运算符重载时,新对象不能在operator =()之外访问,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!