您的 operator+() 严重受损。考虑“期限”所有权的概念。每个多项式都有一个项的链接列表。它拥有这个列表(至少更好)。现在考虑一下对您的简要分析operator +():
Polynomial Polynomial::operator+(const Polynomial & poly) const 
{
    // hopefully creates a deep copy of *this
    Polynomial p2 = *this;
    // walk *our* terms (not the copy in p2??) to find the end.
    term * temp = (*this).ptr;
    while(temp->next != NULL)
        temp = temp->next;
    // once we find the end, we then *LINK* the params term-list
    //  which *they* are **supposed** to own, to our list. (and 
    //  p2 is still out there with a copy of our original content).
    temp->next = poly.ptr;
    // now we return p2, still holding a copy of our former self,
    // and we now have a cross-linked term list between us and the 
    // parameter poly
    return p2;
}
我真诚地希望这有什么问题是显而易见的。为了使它正常工作,您的操作员应该返回一个 by-val,(它就是,万岁!),并正确地制造那个东西:
- 制作*this(你有那个)的副本(让我们称之为p2)
- 查找所拥有的术语列表的末尾p2
- rhs复制 的参数中的所有术语- operator +(const Polynomial* rhs),将副本一一链接到- p2的术语列表的尾部。注意:尾部将随着每个链接的新术语移动。
- 按 val 返回 p2。如果您的复制器和析构器正在完成他们的工作,那么一切都应该很好。完成后,*this 和rhs都应该保持不变。
这就是我能提供的程度。祝你好运。
PS:对于extra-credit-bonus-round,在插入时对列表中的术语进行排序。这将使您更接近相似度合并,这将成为operator +=()您的operator +(). 后者从字面上退化为Polynomial p2 = *this; p2 += poly; return p2;