为什么类里的析构函数delete去掉就可以正确得到,而加上就出现如图二的错误了呢?想了一下午还是想不明白?(┯_┯)!
#include<iostream>
using namespace std;
class complex
{
double *p;
public:
complex(double m=0,double n=0)
{
p=new double[2];
p[0]=m;p[1]=n;
}
//complex(){}
complex(const complex &obj)
{
p[0]=obj.p[0];
p[1]=obj.p[1];
}
~complex()
{
delete[]p;
}
friend complex operator+ ( const complex & c1, const complex & c2 )
{
double r=c1.p[0]+c2.p[0];
double i=c1.p[1]+c2.p[1];
return complex(r,i);
}
friend complex operator- ( const complex & c1, const complex & c2 )
{
double r=c1.p[0]-c2.p[0];
double i=c1.p[1]-c2.p[1];
return complex(r,i);
}
friend complex operator* ( const complex & c1, const complex & c2 )
{
double r=c1.p[0]*c2.p[0]-c1.p[1]*c1.p[1];
double i=c2.p[0]*c1.p[1]+c2.p[1]*c1.p[0];
return complex(r,i);
}
void show()
{
if(p[0]!=0)
{
cout<<p[0];
if(p[1]>0&&p[1]!=1)
{
cout<<'+'<<p[1]<<'i'<<endl;
}
else if(p[1]<0&&p[1]!=-1)
cout<<p[1]<<'i'<<endl;
else if(p[1]==1)
cout<<'+'<<'i'<<endl;
else if(p[1]==-1)
cout<<'-'<<'i'<<endl;
else
cout<<endl;
}
else
{
if(p[1]>0&&p[1]!=1)
cout<<p[1]<<'i'<<endl;
else if(p[1]<0&&p[1]!=-1)
cout<<p[1]<<'i'<<endl;
else if(p[1]==1)
cout<<'i'<<endl;
else if(p[1]==-1)
cout<<'-'<<'i'<<endl;
}
}
};
int main()
{
double q,p,s,e;
cin>>q>>p>>s>>e;
complex a(q,p),b(s,e),c;
char d;
cin>>d;
if(d=='-')
c=a-b;
else if(d=='+')
c=a+b;
else if(d=='*')
c=a*b;
c.show();
return 0;
}