我试图通过重载输入和输出运算符来读取和打印表示为链表的多项式。我必须重载它们两次:一次在类节点中(用于读取和打印单个节点),另一次在类多项式中(使用已经实现的节点I / O重载)。 但是,我用来重载多项式的I / O的朋友函数无法访问类节点的私有成员(类多项式的朋友)。
功能" inserare"只需在多项式中添加一个节点。 我的代码:
using namespace std;
class nod
{
friend class polinom;
int exp,coef;
nod *urm;
friend ostream &operator<<( ostream &output, const nod &X );
friend istream &operator>>( istream &input, nod &X );
};
ostream &operator<<( ostream &output, const nod &X )
{
if(X.coef==0) output<<0;
else if(X.exp==0)
{
if(X.coef>0) output<<"+"<<X.coef;
else output<<X.coef;
}
else if(X.coef>0)
{
if(X.coef==1&&X.exp==1) output<<"+"<<"x";
if(X.coef==1&&X.exp!=1) output<<"+"<<"x^"<<X.exp;
if(X.coef!=1&&X.exp==1) output<<"+"<<X.coef<<"*x";
if(X.coef!=1&&X.exp!=1) output<<"+"<<X.coef<<"*x^"<<X.exp;
}
else
{
if(X.coef==-1&&X.exp==1) output<<"-"<<"x";
if(X.coef==-1&&X.exp!=1) output<<"-"<<"x^"<<X.exp;
if(X.coef!=-1&&X.exp==1) output<<X.coef<<"*x";
if(X.coef!=-1&&X.exp!=1) output<<X.coef<<"*x^"<<X.exp;
}
return output;
}
istream &operator>>( istream &input, nod &X )
{
input>>X.coef;
input>>X.exp;
X.urm=NULL;
return input;
}
class polinom
{
nod *prim,*curent;
public:
polinom(); //constructor
~polinom(); //destructor
polinom(const polinom& p); //copy constructor
void inserare(nod *aux);
friend ostream &operator<<( ostream &output, const polinom &X );
friend istream &operator>>( istream &input, polinom &X );
};
ostream &operator<<( ostream &output, const polinom &X )
{
for(nod* temp = X.prim; temp!= NULL; temp = temp->urm)
output<<temp;
return output;
}
void polinom::inserare(nod *aux)
{
if(prim==NULL&&aux->coef==0)
{
prim=aux;
curent=prim;
}
if(aux->coef)
{
if(prim==NULL||prim->exp>aux->exp)
{
aux->urm=prim;
prim=aux;
curent=prim;
}
else
{
curent=prim;
while(curent->urm&&curent->urm->exp<=aux->exp)
{
curent=curent->urm;
}
if(curent->exp==aux->exp)
{
curent->coef=curent->coef+aux->coef;
return;
}
if(curent->urm==NULL) curent->urm=aux;
else
{
aux->urm=curent->urm;
curent->urm=aux;
return;
}
}
}
}
istream &operator>>( istream &input, polinom &X )
{
nod temp;
do
{
input>>temp;
X.inserare(&temp);
}
while(temp.coef);
return input;
}
答案 0 :(得分:0)
您需要另一组friend
声明,以便polynom
的提取器/插入器可以访问节点的数据成员:
class nod
{
friend class polinom;
int exp,coef;
nod *urm;
friend ostream &operator<<( ostream &output, const nod &X );
friend istream &operator>>( istream &input, nod &X );
friend ostream &operator<<( ostream &output, const class polinom &X );
friend istream &operator>>( istream &input, class polinom &X );
};