重载多项式C++ 中的 I/O 运算符

Overloading i/o operators in C++ for polynomials

本文关键字:运算符 中的 多项式 C++ 重载      更新时间:2023-10-16

我得到了这个项目,我必须重载 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++),然后分配给它。您的成员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 << "0n";
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;
}

(1)

double coef[];

这是在堆栈上具有未调整大小/动态大小的数组的非标准方法。你最好给数组一些大小,或者让它成为一个指针并自己分配内存;或使用vector<double>

(二)您正在构造函数中创建一个局部变量,这将隐藏类中的成员变量。如果您使用的是指针方法,则需要在构造函数中正确分配它。无论使用哪种方法,理想情况下,都应将(成员)变量初始化为零coef

(三)

Polynomial p1();

这有效地声明了一个名为p1的函数,该函数将返回一个Polynomial而不是 tyoePolynomial的变量。您可能希望使用:

Polynomial p1;