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;
}
~Polyn() { cout << "析构函数调用"<<endl; clear(); delete phead; }//野指针？？？？存在-出错
void clear(); //清空
void creatp();//建立链表

void print();//输出
private:

};

void Polyn::clear()
{
PNode *p, *q;
while (p)
{

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

}

}
void Polyn::creatp()
{
int n;
int i = 0;
cout << "请输入多项式项数：";
cin >> n;
PNode *p, *q;
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 pc;
PNode *p1, *p2, *p3;
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;
cout << "empty!!" << endl;
else
while (p)
{
cout << p->data.coef << " " << p->data.expn << " ";
p = p->next;
}
cout << endl;
}

ｍａｉｎ．ｃｐｐ
#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      2016.09.19 00:13