在 Node 成员的类中重载 += 运算符

Overloading the += operator in a class for a Node member

本文关键字:重载 运算符 Node 成员      更新时间:2023-10-16

我正在尝试重载程序中的 += 运算符。它由一个多项式类组成,其中包括一个整数度(多项式的最高次数)和一个节点* 多边形(指向节点的指针)

struct Node{ int coefficient;
             Node* next; };

这是我的节点结构,不过我在多项式类中重载了。

  Polynomial& Polynomial::operator +=(const Polynomial& rP){
    Polynomial copyRP(rP);
    poly->coefficient = poly->coefficient + copyRP.poly->coefficient;
    poly = poly->next; //if I take this and
    copyRP.poly = copyRP.poly->next; //this away, it runs fine
    //with it however the program compiles but doesnt work 
    return *this;
  }

节点包含向后的系数列表(如果这很重要)。 例如,3x^2+2x+5 在节点中存储为 5->2->3,度数为 2。

试试这个:

struct polynomial {
    std::vector< int > coeffs;
    std::size_t degree() const { return coeffs.size(); }
};
polynomial &polynomial::operator+= ( polynomial &lhs, polynomial const &rhs ) {
    if ( lhs.degree() < rhs.degree() ) lhs.coeffs.resize( rhs.degree() );
    for ( std::size_t k = 0; k != rhs.degree(); ++ k ) {
        lhs.coeffs[ k ] += rhs.coeffs[ k ];
    }
    return lhs;
}
没有

链表,没有手动内存管理,您可以轻松地将其更改为另一种数字类型。