When using assignment operator overloading, the new object isn't accessible outside of operator=()

◇◆丶佛笑我妖孽 提交于 2019-12-13 23:09:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!