使用赋值运算符重载时,在operator =()之外无法访问新对象

时间:2015-04-21 17:55:30

标签: c++ operator-overloading

我有一个Queue的实现,它需要编写赋值运算符重载。

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();

};

1 个答案:

答案 0 :(得分:4)

  

operator=()函数看起来怎么样?

operator=应该使用(*this)的值修改内部对象rhs,然后逐字地返回(*this)