【问题标题】:Adding Polynomials Through Linked Lists通过链表添加多项式
【发布时间】:2016-06-03 23:01:18
【问题描述】:

我正在编写通过结构类从用户那里获取两组多项式的代码:

struct Term
{
    double coefficient;
    unsigned exponent;
    Term *next;
};

然后提示要求他们对多项式进行加、减或求值(要求用户输入“x”的值)。我在编写加法和减法函数时遇到了麻烦。到目前为止,我为 add 函数编写了这个,但我不确定如何返回新的多项式。根据我对错误消息的理解,我不能使用类型为TermPtr 的 += 运算符。我不确定如何解决这个问题。

TermPtr add(TermPtr p1, TermPtr p2)
{   
    TermPtr newPoly;

    if (p1 -> exponent == p2 -> exponent)
          newPoly += ((p1 -> coeff) + (p2 -> coeff));

    return newPoly;
}

我收到以下错误:

In function 'Term* add(TermPtr, TermPtr)':
36:19: error: invalid operands of types 'TermPtr {aka Term*}' and 'double' to binary 'operator+'
36:19: error:   in evaluation of 'operator+=(using TermPtr = struct Term* {aka struct Term*}, double)'

【问题讨论】:

  • 您的签名需要两个术语指针,并且您使用术语指针和双精度值进行调用。您需要为 (TermPtr, double) 提供 operator+ 重载。

标签: c++ linked-list nodes


【解决方案1】:

由于 TermPtr 是 Term* 的 typedef,因此您的代码正在尝试递增指针。如果你想返回一个指针,那么下面的代码应该可以解决问题,但是返回一个指向新术语的指针意味着你必须手动管理内存并在以后删除它,或者泄漏内存。

 TermPtr add(TermPtr p1, TermPtr p2)
    {   
        TermPtr newPoly = new Term();
        newPoly -> exponent = p1 -> exponent;
        if (p1 -> exponent == p2 -> exponent){
              newPoly -> coeff += ((p1 -> coeff) + (p2 -> coeff));
        }


        return newPoly;
    }

请记住,如果指数不匹配,您仍然会得到一个新项(系数等于 0,假设您的默认构造函数将 0 分配给 coeff)。

你可能想做的是这样的:

Term add(TermPtr p1, TermPtr p2)
{   
    Term newPoly;
    newPoly.exponent = p1 -> exponent;
    if (p1 -> exponent == p2 -> exponent){
          newPoly.coeff += ((p1 -> coeff) + (p2 -> coeff));
    }


    return newPoly;
}

这样您以后不必自己管理内存。

至于一般的想法,您可能需要在调用 add 之前检查指数,以免以空项结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多