问题
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?
EDIT: 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();
};
回答1:
How is an
operator=()
function supposed to look?
An operator=
is supposed to modify the internal object (*this)
with the values of rhs
and then literally return (*this)
.
来源:https://stackoverflow.com/questions/29779731/when-using-assignment-operator-overloading-the-new-object-isnt-accessible-outs