我得到了这个项目,在这里我必须重载I / O运算符以读取和写入多项式。不幸的是,我似乎无法使其正常工作。

我有头文件:

#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <iostream>

using namespace std;

class Polynomial
{
public:
    Polynomial();

Polynomial(int degree, double coef[]);

int degree;
double coef[ ];
friend istream& operator>>(istream&,Polynomial& );
friend ostream& operator<<(ostream&,const Polynomial&);

virtual ~Polynomial();
 };
#endif // POLYNOMIAL_H


和cpp文件:

#include "Polynomial.h"
#include<iostream>
#include<string>

using namespace std;

Polynomial::Polynomial()
{
    //ctor
}

Polynomial::~Polynomial()
{
    //dtor
}

Polynomial::Polynomial(int d, double c[])
{
    degree = d;
    double coef [degree+1];
    for(int i = 0; i < d+1; i++)
    {
        coef[i] = c[i];
    }

}

istream& operator>>(istream& x, const Polynomial& p)
{
    cout<<"The degree: ";
    x>>p.degree;

    for(int i = 0; i < p.degree+1; i++)
    {
        cout<<"The coefficient of X^"<<i<<"=";
        x>>p.coef[i];
    }
    return x;
}

ostream& operator<<(ostream& out, const Polynomial& p)
{
    out << p.coef[0];

    for (int i = 1; i < p.degree; i++)
    {
        out << p.coef[i];
        out << "*X^";
        out << i;
    }

    return out;
}


我正试图读取一个多项式,然后再写一个:

#include <iostream>
using namespace std;
#include "Polynomial.h"

int main()
{
    Polynomial p1();
    cin >> p1;

    int degree = 2;
    double coef [3];
    coef[0]=1;
    coef[1]=2;
    coef[3]=3;

    Polynomial p(degree, coef);

    cout<<p;


    return 0;
}


当我运行程序时,它只是冻结了,我似乎找不到错误。
有任何想法吗?

最佳答案

Polynomial::Polynomial(int d, double c[])
{
    degree = d;
    double coef [degree+1];
    for(int i = 0; i < d+1; i++)
    {
        coef[i] = c[i];
    }

}


在这里,您创建本地数组coef(使用非标准C ++ btw),然后分配给它。您的成员coeff未被初始化为任何有意义的东西(并且一开始它的当前状态几乎没有意义)。

代替double coef[],您应该像这样使用std::vector

struct polynomial {
    std::vector<double> coef;
    // No need for member varaible degree, vector knows its lengths
    polynomial (const std::vector<double> &coeffs) : coef (coeffs) {}
};


然后定义所有其他构造函数,您需要做一些有意义的事情。或者,您可以完全省略构造函数,直接分配系数向量。然后您可以例如使用以下功能

int degree (const polynomial &p) {
    return p.coef.size() - 1;
}


要么

std::ostream &operator << (std::ostream &out, const polynomial p) {
    if (p.coef.size() == 0) {
        out << "0\n";
        return out;
    }
    out << p.coeff[0];
    for (int i = 1; i < p.coef.size(); ++i)
       out << " + " << p.coef[i] << "*X^i";
    out << "\n";
    return out;
}

09-07 04:04