2 qq 34982491 qq_34982491 于 2016.09.18 21:38 提问

c++中析构函数出现问题

#pragma once
#include
using namespace std;
struct term
{
double coef;//{数} coefficient 系数
int expn;//exponent 指数

};
struct PNode
{
term data;
PNode *next;
};
class Polyn //polynomial 多项式
{
public:
Polyn()
{
cout << "构造函数调用"< phead = new PNode;
phead->next = NULL;
}
~Polyn() { cout << "析构函数调用"<<endl; clear(); delete phead; }//野指针????存在-出错
void clear(); //清空
void creatp();//建立链表
Polyn PolyAdd(Polyn pb);//多项式求和

void print();//输出
private:
PNode *phead;

};

void Polyn::clear()
{
PNode *p, *q;
p = phead->next;
while (p)
{

    q = p->next;
    delete p;
    p = q;

}
phead->next = NULL;

}
void Polyn::creatp()
{
int n;
int i = 0;
cout << "请输入多项式项数:";
cin >> n;
PNode *p, *q;
q = phead;
for (i = 0; i < n; i++)
{
p = new PNode;
//cout << "输入系数:" << endl;
cin >> p->data.coef;
//cout << "输入指数:"< cin >> p->data.expn;
p->next = NULL;
q->next = p;
q = p;
}
}
Polyn Polyn::PolyAdd(Polyn pb)
{
Polyn pc;
PNode *p1, *p2, *p3;
p1 = phead;
p2 = pb.phead;
p3 = pc.phead;
PNode *t1, *t2, *t3;
t1 = p1->next;
t2 = p2->next;
t3 = p3;
while (t1&&t2)
{
if (t1->data.expn < t2->data.expn)
{
t3->next = new PNode;
t3 = t3->next;
t3->data = t1->data;
t1 = t1->next;
}
else if (t1->data.expn > t2->data.expn)
{
t3->next = new PNode;
t3 = t3->next;
t3->data = t2->data;
t2 = t2->next;
}
else
{
double a = t1->data.coef + t2->data.coef;
if (a != 0.0)
{
t3->next = new PNode;
t3 = t3->next;
t3->data.coef = a;
t3->data.expn = t1->data.expn;
}
t1 = t1->next;
t2 = t2->next;
}
}
while (t1 != NULL)
{
t3->next = new PNode;
t3 = t3->next;
t3->data = t1->data;
t1 = t1->next;
}
while (t2 != NULL)
{
t3->next = new PNode;
t3 = t3->next;
t3->data = t2->data;
t2 = t2->next;
}
t3->next = NULL;
return pc;
}

void Polyn::print()
{
PNode *p;
p = phead->next;
if (phead->next == NULL)
cout << "empty!!" << endl;
else
while (p)
{
cout << p->data.coef << " " << p->data.expn << " ";
p = p->next;
}
cout << endl;
}

main.cpp
#include
#include"polynomial.h"
using namespace std;
int main()
{
Polyn s,s2;
cout << "输入多项式1:" << endl;
s.creatp();
cout << "输入多项式2:" << endl;
s2.creatp();
s2.print();

cout << "相加为:" << endl; s.PolyAdd(s2).print();
//s3.print();
/*s3.clear();//error 出错,完全相同可运行
s2.clear();
s.clear();
/*s.creatp();
s.print();*/

}
//realloc
以上是代码运行到相加时会停止,求大神解答

1个回答

devmiao
devmiao   Ds   Rxr 2016.09.19 00:13
Csdn user default icon
上传中...
上传图片
插入图片