【问题标题】:When using assignment operator overloading, the new object isn't accessible outside of operator=()使用赋值运算符重载时,在 operator=() 之外无法访问新对象
【发布时间】: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();

};

【问题讨论】:

  • 如果没有看到Queue class,很难说它应该是什么样子。不过,杰弗里几乎确定了答案。
  • 您使用 new/delete 完全错误 - 在您知道如何配对 new/delete 或将删除委托给智能指针之前避免使用它。
  • return * newlist;rhs.head == NULL 时是未定义的行为,因为此时newlist 是一个未初始化的指针。
  • 我已经包含了 queue.h 但如果没有 linkedlist.h 可能就没有用了。

标签: c++ operator-overloading


【解决方案1】:

operator=() 函数应该是什么样子?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多